简体   繁体   中英

.NET Core Dependency Injection - Multiple Projects

My group of projects is as follows:

1) Shared Class Library

  • Models
  • Entity Framework Classes (DB Contexts etc)

2) Web API

  • Uses the models and entity framework classes in (1) to communicate with the database.

3) Console Application

  • Creates instances of Models in (1) and saves them to the database using the entity framework classes there.

My question is:

Should I be creating a single DI Container class that has a ConfigureServices method that is shared between both the Console Application and the Web API?

Or does it make more sense for each of these applications to be responsible for binding their own dependencies?

Thanks in advance!

Ioc registrations

It depends on the nature of applications but in general i would say you want to split it up and have it in either application. Things that are the same in both application don't need abstraction and ioc registration (don't make things abstract that are not needed to be abstract).

That said, you see microsft uses the extension method pattern to add multiple demendencies at once like: services.AddMvc() is an extentension method to add 20 or so ioc registrations. You could do the same in your shared library. and simply add services.AddSharedLibrary() in your startup classes:

public static class MyServiceExtensions 
{
     public static IServiceCollection AddMyLibrary(this IServiceCOllection services)
     {
         services.Add<Interface1,Implemenetation1>();
         services.Add<Interface2,Implemenetation2>();
         return services;
     }
}

Startup base class

You can also make an (abstract) base class for the Startup Class. But this would mean that your Shared library now needs dependencies on the HttpBuilder/Kestrel nuget package. which would be weird if you where making a Servicebus queue listener for example.

A good reason to make a base class for Startup is: if you want all your startup projects to have the same way and order to build up the Appsettings and/or you want them to use the same Appsettings as configuration for IOptions. But in this case i would recommend making a separate shared library for this that is specifically aimed to provide the same StartupBase and configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM