1

I want to use dependency injection in class library build on .NET Standard 5. Also the class library dont have the startup.cs file so i can't inject my dependencies.

Is there anything i am missing here?

Kindly advise.

  • 2
    First, clearly identify what you're trying to work with. There is *no such thing* as .NET Standard 5. Also, dependency injection is usually the responsibility of the "host" application, not something class libraries need to/should concern themselves with. – Damien_The_Unbeliever Jun 08 '21 at 15:59
  • Some libraries provide extension methods that the "host" application can call to have the library register itself with the DI container spun up by the application. – jmoerdyk Jun 08 '21 at 16:04
  • You should take a look at my [that](https://stackoverflow.com/a/67849630/13664939) answer – gurkan Jun 08 '21 at 16:16
  • 1
    There is a big difference between a class library that is part of a solution and a class library that is shipped independently (possibly through NuGet). In case the class library is part of a (single) solution, the answer is that you place the registrations inside the [Composition Root](https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/). If the library, however, is a separate deployable, you should follow the practice of [DI-friendly libraries](https://blog.ploeh.dk/2014/05/19/di-friendly-library/). – Steven Jun 14 '21 at 10:43

1 Answers1

1

One option would be to write an extension method for IServiceCollection that registers your dependencies. Something like:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddServices(this IServiceCollection services)
    {  
        return services
            .AddTransient<IService1, Service1>()
            .AddTransient<IService2, Service2>();
    }
}

It would be the responsibility of the application consuming your library to call this method to register the dependencies.

Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61