我对使用 DI 容器还比较陌生,并且遇到了一些障碍。
SimpleInjector 有一个具有以下签名的方法:
Container.RegisterInitializer<TService>(Action<TService>)
在我们的代码库中,我们确实像这样使用它:
// this is a property injection of the abstract file system
container.RegisterInitializer<IFileSystemInjection>(
fs => fs.FileSystem = new FileSystem());
我想知道如何使用 Startup.cs 类中的ConfigureServices 方法中的IServiceCollection 参数来实现相同的目的。到目前为止,我已经能够使用 services.AddTransient(); 注册所有类型。但我不确定 IServiceCollection 中的等效 simpleinjector.RegisterInitializer 是如何的。
您可以使用工厂重载AddSingleton
, AddScoped
, and AddTransient
。我不确定范围是什么IFileSystemInjection
应该在,但它sounds就像可能是单身人士的东西。如果没有,请适当更改您调用的方法:
service.AddSingleton<IFileSystemInjection>(p =>
{
var fs = new FileSystemInjection();
fs.FileSystem = new FileSystem();
});
简而言之,如果您提供一个工厂,那么您就负责整个对象的初始化,因此new FileSystemInjection()
,我将其作为实际实现IFileSystemInjection
你的使用。
如果该实现具有需要注入才能创建它的依赖项,您可以从p
,这是一个实例IServiceProvider
:
var myDep = p.GetRequiredService<MyDep>();
var fs = new FileSystemImplementation(myDep);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)