简体   繁体   中英

DbContext and Autofac

I have problem with registration of System.Data.Entity.DbContext in Autofac. 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:

An exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll but was not handled in user code

Additional information: An exception was thrown while activating WpfApplication2.DeviceService -> WpfApplication2.Device -> System.Data.Entity.DbContext.

I can't find solution in Google. What is the solution?

I found out that injection of System.Data.Entity.DbContext by Autofac is imposible. But you can inject inherited object of that DbContext -> MyContext: DbContext ->

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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