我目前正在用 C# 实现一个库。 我的主班叫
Foo
。它实现了接口IFoo
。
我正在使用 Microsoft 的依赖注入库来注入此依赖项和其他依赖项。
我的想法是将以下代码添加到我的服务提供商类中:
public static IFoo GetFoo()
{
return ServiceProvider.GetService<IFoo>();
}
因此集成商不必知道如何构建
Foo
的实例并向其注入依赖项。而集成商只知道接口。
我对这个主题做了一些研究,但我没有找到关于这个主题的任何标准或最佳实践。
所以我的问题是有没有任何标准或最佳实践,我的解决方案有什么缺点吗?
谢谢!
非常常见的方法是提供一个方法,通常在像
MyLyb.Extensions.DependencyInjection
这样的命名空间中(有时甚至在Microsoft.Extensions.DependencyInjection
中,尽管在这种情况下你应该有非常具体的名称)可以根据用例放入不同的库中.然后暴露注册:
namespace MyLyb.Extensions.DependencyInjection;
public static class MyLybRegistrationExtensions
{
// possibly add another parameter to provide/setup the SDK settings
public static IServiceCollection AddMyLib(this IServiceCollection services)
{
// registration goes here
return services;
}
}
此方法还可以公开操作以设置库的选项 -
public static IServiceCollection AddMyLib(this IServiceCollection services, Action<MyLibOptions> setOptions = null)
例如 - AutoMapper 与 ASP.NET Core 的集成。