cla*_*amp 3 .net c# dependency-injection unity-container microsoft-extensions-di
我正在将 .NET 应用程序依赖注入框架从 .NET 迁移Unity Container到Microsoft.Extensions.DependencyInjection.
现在我没有找到将接口的现有实例注册到 serviceCollection 的方法。在 Unity 中,这可能是这样的:
_unityContainer.RegisterInstance<IInterface>(myObject);
Run Code Online (Sandbox Code Playgroud)
在IServiceCollection我只找到AddSingleton, AddScoped,AddTransient所有这些都只接受类型。
(我知道这样做一开始可能是不好的做法,但不幸的是它不在我的控制之下。)
AddSingleton<T>接受实现实例有一个重载,例如:
services.AddSingleton<IInterface>(myObject);
Run Code Online (Sandbox Code Playgroud)
此外,还有AddScoped<T>和的重载AddTransient<T>,它们接受工厂函数作为参数。所以你可以像这样注册你的接口:
services.AddScoped<IInterface>((prov) => myObject);
services.AddTransient<IInterface>((prov) => myObject);
Run Code Online (Sandbox Code Playgroud)
但是,如果您始终返回相同的实例,则后者错过了每个范围都有一个实例或瞬态实例的要点 - 这与单例注册更好地匹配。这解释了为什么与orAddSingleton<T>相比有一个特殊的重载。AddScoped<T>AddTransient<T>