I'm new to asp.net core.
What I'm trying to do is to build multi projects solution and use dependency injection to pass interfaces between projects.
What I know is that in ASP.NET core project we have ConfigureServices
method in startup.cs
file to register our interfaces and their implementations like this:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<IMyInterface,MyImplementation>();
.....
}
This is good if you have classes all in the same project, but what if I have multi projects ?
Usually what I'll do is create separate project with installers (Windsor installers) to register the needed interfaces and their implementations.
In .net core we can do this by creating static ServiceCollection();
and get from it static IServiceProvider
to use it any time to get any service you register:
public static IServiceCollection _serviceCollection { get; private set; }
public static IServiceProvider serviceProvider { get; private set; }
public static RegisterationMethod() {
_serviceCollection = new ServiceCollection();
_serviceCollection.AddSingleton<IMyInterface,MyImplementation>();
.....
serviceProvider = _serviceCollection.BuildServiceProvider();
}
public T GetService<T>() where T : class
{
return serviceProvider.GetService<T>();
}
Now we call RegisterationMethod
from ower startup project and continue to develop as usual with always registering the services in this class.
The problem in this approach is if I used it in ASP.NET core project I'll have two places to register the services, this one and the one in the startup.cs
file which has ConfigureServices(IServiceCollection services)
.
You may say,
OK pass
IServiceCollection
you had inConfigureServices(IServiceCollection services)
to theRegisterationMethod
you previously created, in this way you're using the same services collection that ASP.NET using.
But in this way I'll be tight coupled to the dependency injection module of the .net core
.
Is there more clean way to do this ? or should I have replace the default DI with Windsor
for example ?