简体   繁体   中英

NET Core: How do I inject multiple services into a controller?

Please bear with me if I have misunderstood something fundamental, but...

Assuming a Controller need several dependency injected services, like a DBContext, an AutoMapper, maybe some other registered service (of course properly registered in the Startup class), is that possible?

Pseudo-code for a single injected service:

class MyController 
{
    private DBContext _context;

    MyController(DBContext context)
    {
        _context = context;
    }    
}

But if I need several services, like (again just pseudo code):

class My2ndController 
{
    private DBContext _context;
    private IMapper _mapper;
    private SomeConfig _config;

    My2ndController(DBContext context, IMapper mapper, SomeConfig config)
    {
        _context = context;
        _mapper = mapper;
        _config = config;
    }    
}

Is that possible?

Yes that's possible, you'll just need to make sure you register your service in your Startup.cs .

In your ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
     // . . . code above

    services.AddTransient<IMapper, Mapper>();

    /// . . . code below
}

Now any controller that requires an IMapper interface will be passed the Mapper class upon creation.

Also, just know there are other lifetimes besides Transient. Such as Singleton, where there can only be 1 instance of that class.

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