I have an ASP.NET Core Web API project with class libraries. I can register dependency of class library which are directly added as references into the project. But I am not able to find way to register dependency of class library which are not directly added to the project.
For example, as you can see in following screenshot:
It is the ASP.NET Core Web API project.
It has a class library
FirstClasslibproject.The
FirstClasslibproject is added as reference to the ASP.NET Core Web API project.FirstClasslibproject has dll reference ofSecondClasslibproject.SecondClasslibis also a library with interface and its implementation as shown in the following screenshot:
I want to register dependencies of SecondClasslib through DI like I did for FirstClasslib. But since it is not directly linked to the ASP.NET Core Web API project, how can I do this?
Please find source code repo at https://github.com/sujadkar/WebApplication1
I tried BuildServiceProvider approach but many people are saying it is anti pattern and we should avoid. I want to resolve dependency of SecondClasslib using Dependency Injection.
Edit 1 - Instead of using the Extension method and calling method from the Startup.cs class Can we use the following approach?
In secondclasslib could we add the following
public class SecondFactory
{
public static ISecondClass CreateProvider() {
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddTransient(typeof(ISecondClass),typeof(SecondClassImplementation));
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
ISecondClass secondClass = serviceProvider.GetRequiredService<ISecondClass>();
return secondClass;
}
}
In firstclasslib we can get instances using the following code,
public class FirstClassImplementation : IFirstClass
{
public void SubmitRequest(int hello)
{
ISecondClass secondClass = SecondFactory.CreateProvider();
}
}
Could you please tell me if this is the correct approach for dependency registration and getting instances?


If you don't want your API project to add a reference to
SecondClassLib, then in yourFirstClassLibproject, create an extension method like this:Then in your Web API project, use:
For multiple projects, you need a compose root project to register all services as above and your main project to refer to this project