Reputation: 28545
Im using simple injector.
I have an mvc project that also has ApiControllers.
Here is my setup:
public static class SimpleInjectorWebApiInitializer
{
/// <summary>Initialize the container and register it as Web API Dependency Resolver.</summary>
public static void Initialize()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
InitializeContainer(container);
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
// This is an extension method from the integration package.
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
// GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
}
private static void InitializeContainer(Container container)
{
container.Register<DbContext, CoreContext>(Lifestyle.Scoped);
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
}
}
However this gives me the error:
The configuration is invalid. The following diagnostic warnings were reported: -[Lifestyle Mismatch] UnitOfWork (Async Scoped) depends on CoreContext (Transient).
Upvotes: 2
Views: 525
Reputation: 172776
Your UnitOfWork
class depends on CoreContext
, but you didn't register CoreContext
as a service, but only as an implementation. Simple Injector will only look for registration of services, but a registration for CoreContext
is missing. As fallback, Simple Injector will try to resolve CoreContext
directly, which works because it is a concrete type. Those unregistered concrete types, however, are, by default, resolved using the Transient lifestyle.
Resolving a DbContext implementation as Transient, however, is typically not something you want. Scoped is typically better and Simple Injector is therefore correct in warning about this.
You should change your registration to the following:
container.Register<CoreContext>(Lifestyle.Scoped);
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);
Upvotes: 1