I'm currently implementing a library in C#.
My main class is called Foo
. It implements the interface IFoo
.
I'm using the Dependency Injection library from Microsoft to inject this and other dependencies.
My idea was to add the following code to my service provider class:
public static IFoo GetFoo()
{
return ServiceProvider.GetService<IFoo>();
}
So the integrator does not have to know how to build an instance of Foo
and inject the dependencies to it. And the integrator only knows the interface.
I done some research about this topic but I do not find any standards or best practices about this topic.
So my question is: are there any standards or best practices and does my solution have any disadvantages?
The quite common approach is to provide a method, usually in namespace like MyLyb.Extensions.DependencyInjection
(sometimes even in Microsoft.Extensions.DependencyInjection
though you should have very specific name in this case) which can be put into a different library, depending on the use case. And then expose the registration:
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;
}
}
Also this method can expose action to set the options for the library - public static IServiceCollection AddMyLib(this IServiceCollection services, Action<MyLibOptions> setOptions = null)
For example - AutoMapper's integration with ASP.NET Core.