C# 通过多个抽象注册类,同时手动创建类型

C# 通过多个抽象注册类,同时手动创建类型,c#,simple-injector,C#,Simple Injector,我想注册类Foo及其接口IBar var b = new DbContextOptionsBuilder(); b.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=Connect.Device;Trusted_Connection = True; MultipleActiveResultSets = true;"); _container.Register(() => new DeviceContext(b.Options), L

我想注册类
Foo
及其接口
IBar

var b = new DbContextOptionsBuilder();
b.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;Database=Connect.Device;Trusted_Connection = True; MultipleActiveResultSets = true;");
_container.Register(() => new DeviceContext(b.Options), Lifestyle.Scoped);
_container.Register<IFoo, DeviceContext>(Lifestyle.Scoped);
_container.Register<IDeviceTypeService, DeviceTypeService>(Lifestyle.Scoped);
var b=new DbContextOptionsBuilder();
b、 使用SQLServer(@“服务器=(localdb)\MSSQLLocalDB;数据库=Connect.Device;可信连接=True;MultipleActiveResultSets=True;”);
_container.Register(()=>newdeviceContext(b.Options),lifesture.Scoped);
_容器。寄存器(生活方式。范围);
_容器。寄存器(生活方式。范围);
这是行不通的。这是调用
验证时引发的异常:

System.InvalidOperationException HResult=0x80131509消息= 配置无效。为类型IFoo创建实例失败。 DeviceContext类型的构造函数包含名为的参数 “options”并键入未注册的DbContextOptions。请 确保已注册DbContextOptions,或更改的构造函数 设备上下文。Source=SimpleInjector StackTrace:at SimpleInjector.InstanceProducer.VerifyExpressionBuilding()位于 验证是否可以生成所有表达式(InstanceProducer[] 生产商(验证)在 验证AllExpressionsCanbebuild()是否可以在 SimpleInjector.Container.VerifyInternal(布尔值 抑制(不匹配验证)在 SimpleInjector.Container.Verify(VerificationOption选项)位于 Connect.Device.Service.Startup.InitializeContainer(IAApplicationBuilder app)在启动中。cs:85行 Connect.Device.Service.Startup.Configure(IApplicationBuilder应用程序, IHostingEnvironment env)在Startup.cs中:第50行

内部异常1:ActivationException:类型为的构造函数 DeviceContext包含名为“options”且类型为的参数 未注册的DbContextOptions。请确保 DbContextOptions已注册,或更改的构造函数 设备上下文


使用
寄存器
(例如您的
寄存器
)的注册总是通过分析类型的构造函数来使用自动连接。它不会重用以前使用委托的注册

您希望覆盖自动布线和手动布线
DeviceContext
,同时能够通过多种类型来解析它。实现这一目标的方法如下:

var reg = Lifestyle.Scoped.CreateRegistration(
    () => new DeviceContext(b.Options), container);
container.AddRegistration<DeviceContext>(reg);
container.AddRegistration<IFoo>(reg);
var reg=lifety.Scoped.CreateRegistration(
()=>新设备上下文(b.Options),容器);
集装箱登记(reg);
集装箱登记(reg);

这里您为
DeviceContext
创建了一个
Registration
实例,它允许您手动连接类型,同时指定其生活方式。但是,这并不注册它,这可以通过调用
AddRegistration
来完成,同时指定可以解析它的类型。

请发布确切的异常消息。请确保您的代码是MCVE(即确保它是编译的)。@Steven更新了问题。我没有看到任何关于类具有默认构造函数的信息。@Steven Ok,它抱怨
DeviceContext
没有无参数构造函数,但构造函数需要未注册的参数。问题是为什么container忽略了一个事实,
DeviceContext
已经注册。@Steven这是一个后续问题。我刚刚尝试将
DeviceContext
注册从
ConfigureServices
移动到
InitializeContainer