I'm trying to implement composition roots for my solution consisting of multiple applications and several class libraries. I'm using Simple Injector as my DI framework of choice.
Having multiple applications requires multiple composition roots. However, I do not want to have duplicate container registrations in every composition root. I'm therefore considering using the approach mentioned in https://stackoverflow.com/a/11993030/852765 , but have run into problems.
How do I override the lifecycles for registrations on application basis? Specifically, I want to override some container registrations to have a "per Web API request lifecycle" in my Web API application, while my other applications use a transient lifecycle for the same registration.
The trick is to pass one of the scoped lifestyles onto the centralized part of the composition root. You can do that by using the ScopedLifestyle
base class:
public static class BusinessLayerBootstrapper
{
public static void Bootstrap(Container container, ScopedLifestyle scopedLifestyle)
{
container.Register<IUnitOfWork, MyDbContext>(scopedLifestyle);
// etc...
}
}
In your end application you can call this as follows:
public class Global : Application
{
protected override Application_Start()
{
var container = new Container();
container.RegisterMvcControllers();
BusinessLayerBootstrapper.Bootstrap(container, new WebRequestLifestyle());
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
Although this same works when using the Lifestyle
base class itself, this class lacks some functionality that you might be interested in, such as RegisterForDisposal
, GetCurrentScope
and WhenScopeEnds
.
Passing the ScopedLifestyle
even works when you create hybrid lifestyles, since there is a Lifestyle.CreateHybrid
overload that takes in two ScopedLifestyle
instances and returns a new ScopedLifestyle
instance:
ScopedLifestyle mixedScopeLifestyle = Lifestyle.CreateHybrid(
() => HttpContext.Current != null,
new WebRequestLifestyle(),
new LifetimeScopeLifestyle());
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.