SimpleInjector mixed lifestyle for per web request and lifetime scope

爱⌒轻易说出口 提交于 2019-12-05 13:11:06

I am not entirely satisfied with this solution

Yes, I agree with this. To be honest, having to do things like this actually sucks IMO. That's why this is fixed in Simple Injector 2.0. It contains the explicit notion of lifestyle and it will contain a Lifestyle.CreateHybrid method, that makes it much easier to register hybrid lifestyles.

You however, don't seem to need a hybrid lifestyle add all. A hybrid lifestyle is a lifestyle that can switch dynamically (on each call to GetInstance<T> and per each injection), while you only seem to need to switch during start-up. I see no harm in using the RegisterHybridLifestyle extension method as you defined it, but keep in mind that this is not really an hybrid lifestyle (so the name is a bit misleading), but simply a configuration/deployment-switch.

Simple Injector 2 and up make this much easier, and it will allow you to do something like this:

// Define a lifestyle once based on the deployment.
Container.Options.DefaultScopedLifestyle =
    Lifestyle.CreateHybrid(
        lifestyleSelector: HostingEnvironment.ApplicationHost != null,
        trueLifestyle: new WebRequestLifestyle(),
        falseLifestyle: new LifetimeScopeLifestyle());

// And use it for registering the unit of work
// (no extra interfaces needed anymore).
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);

// After setting DefaultScopedLifestyle, you can usr Lifestyle.Scoped
container.RegisterCollection(
    typeof(ISubscriber<>),
    new [] { typeof(ISubscriber<>).Assembly },
    Lifestyle.Scoped);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!