I am using unit of work pattern for my transitions. I created an DbContext which is handling connection, commit, rollback works.
In my data access and business layer classes, I inject IDbContext by constructors.
public TestDAL(IDbContext dbContext) : base(dbContext) {}
public TestService(IDbContext dbContext, ITestDAL testDAL) {}
I moved simple injector from autofac. I'm getting an exception about lifestyle mismatch.
-[Lifestyle Mismatch] TestService (Async Scoped) depends on IDbContext implemented by DbContext (Transient).
-[Lifestyle Mismatch] TestDAL (Async Scoped) depends on IDbContext implemented by DbContext (Transient).
I register my DAL and Service classes as scoped and DbContext as transient.
var ServiceRegistrations =
from type in Assembly.GetExecutingAssembly().GetTypes()
where type.Name.EndsWith("Service") && type.IsClass
from service in type.GetInterfaces()
select new { service, type };
foreach (var reg in ServiceRegistrations)
{
container.Register(reg.service, reg.type, Lifestyle.Scoped);
}
container.Register<IDbContext, DbContext>(Lifestyle.Transient);
I read some about DbContext should be transient, it is not thread safe. Also I think DAL and Service classes not necessary to create transient. How can I fix this situation? Btw, that was not problem at autofac.