简单的喷射器将具体类型与生活方式结合起来

Dan*_* S. 2 c# dependency-injection simple-injector

我正在寻找一种可以使用指定的生活方式注册具体类型的方法,基本上如下所示。

public void SomeFunction( Type concrete, Lifestyle lifestyle ) =>
    container.Register( concrete, lifestyle );
Run Code Online (Sandbox Code Playgroud)

Ste*_*ven 5

当要在简单注入器中进行单个一对一映射时,实际上只有一种方法:

Container.Register(Type serviceType, Type implementationType, Lifestyle lifestyle);
Run Code Online (Sandbox Code Playgroud)

所有其他方法只是此方法的方便重载或“快捷方式”。例如下面的方法:

Container.Register<TService, TImplementation>(Lifestyle)
Run Code Online (Sandbox Code Playgroud)

最终通过调用 回到非泛型重载Register(typeof(TService), typeof(TImplementation), lifestyle)

这同样适用于不接受 a 的重载Lifestyle

Container.Register<TService, TImplementation>()
Run Code Online (Sandbox Code Playgroud)

他们只是通过为给定的实现类型提供确定的生活方式来转发呼叫,这是 - 在默认配置下 - 是瞬态生活方式:Register<TService, TImpementation>(Lifestyle.Transient)

并且有多个重载允许注册具体类型的快捷方式,例如:

Container.Register<TConcrete>()
Run Code Online (Sandbox Code Playgroud)

此方法将调用转发到Register<TConcrete, TConcrete>(). 换句话说,TConcrete是为TService和提供的TImplementation。所以最终,这个调用以Register(typeof(TConcrete), typeof(TConcrete), Lifestyle.Transient).

因此,长话短说,以下方法允许您使用生活方式注册具体类型:

Register<TConcrete>(Lifestyle.Scoped)
Register<TConcrete, TConcrete>(Lifestyle.Scoped)
Register(typeof(Concrete), typeof(Concrete), Lifestyle.Scoped);
Run Code Online (Sandbox Code Playgroud)