简体   繁体   English

DbContext 和 Autofac

[英]DbContext and Autofac

I have problem with registration of System.Data.Entity.DbContext in Autofac.我在 Autofac 中注册 System.Data.Entity.DbContext 时遇到问题。 Constructors of my classes are:我的类的构造函数是:

public DeviceService(IDevice device)
{
   _device = device;
}
public Device(DbContext con)
{
   _localDb = con;
}

I tried this:我试过这个:

_container = new ContainerBuilder();            
_container.RegisterType<DbContext>().As<DbContext>().InstancePerLifetimeScope();
_container.RegisterType<Device>().As<IDevice>();
_container.RegisterType<DeviceService>().As<IDeviceService>();
_dependencyContainer = _container.Build();

But It didn't work because when I tried resolve _dependencyContainer.Resolve<IDeviceService>() , I got this exception:但它没有用,因为当我尝试 resolve _dependencyContainer.Resolve<IDeviceService>()时,我得到了这个异常:

An exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll but was not handled in user code Autofac.dll 中出现“Autofac.Core.DependencyResolutionException”类型的异常,但未在用户代码中处理

Additional information: An exception was thrown while activating WpfApplication2.DeviceService -> WpfApplication2.Device -> System.Data.Entity.DbContext.附加信息:激活 WpfApplication2.DeviceService -> WpfApplication2.Device -> System.Data.Entity.DbContext 时引发异常。

I can't find solution in Google.我在 Google 中找不到解决方案。 What is the solution?解决办法是什么?

I found out that injection of System.Data.Entity.DbContext by Autofac is imposible.我发现 Autofac 注入 System.Data.Entity.DbContext 是不可能的。 But you can inject inherited object of that DbContext -> MyContext: DbContext ->但是您可以注入该 DbContext -> MyContext: DbContext -> 的继承 object

_container.RegisterType<MyContext>().AsSelf()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM