简体   繁体   中英

Dependency Injection with Generic Interface and Simple Injector

I am trying to implement dependency injection with Simple Injector and ASP.NET Core. I have a class library for services and another class library for data access with repositories. My problem is, I have implemented dependency injection in my startup class (web api) to reference my services. Now I need to do the same in the services to injection dependency for repositories. But I don't have a startup class in my class library (services class library), so how can I do it?

public interface IBaseService<TEntity> where TEntity : class
    { }

Account service

    public interface IAccountService : IBaseService<User>
{ }


 private readonly IAccountRepository _repository;
    private readonly IUnitOfWork _unitOfWork;

    public AccountService(IAccountRepository repository, IUnitOfWork unitOfWork) : base (repository, unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }

Repository (in a different class library):

   public interface IBaseRepository<TEntity> where TEntity : class
{}

Your question boils down to the following simple question:

Where should we compose object graphs?

The answer to this question is:

As close as possible to the application's entry point.

This entry point is commonly referred to as the Composition Root .

In other words, all your dependencies should be wired up in the Composition Root, independently of in which layer they live. Your Composition Root is a layer on its own, and it knows about every other part of the system (as explained here ).

So considering the displayed code, your Composition Root might look something as follows:

container.Register<IAccountService, AccountService>();
container.Register<IAccountRepository, AccountRepository>();
container.Register<IUnitOfWork, UnitOfWork>(Lifestyle.Scoped);

Long story short, libraries don't have a Composition Root and you don't wire dependencies in the library itself. You compose all object graphs solely in the startup project.

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