NET Core:如何将多个服务注入控制器?

如果我误解了一些基本知识,请忍受,但是...

假设Controller需要几个依赖项注入服务,例如DBContext,AutoMapper,也许还有其他一些注册的服务(当然已经在Startup类中正确注册了),可以吗?

单个注入服务的伪代码:

class MyController 
{
    private DBContext _context;

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

但是如果我需要多种服务,例如(再次是伪代码):

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

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

有可能吗?

dingdingzhengwei 回答:NET Core:如何将多个服务注入控制器?

是的,您只需要确保在Startup.cs中注册服务即可。

在您的ConfigureServices方法中:

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

    services.AddTransient<IMapper,Mapper>();

    /// . . . code below
}

现在,所有需要使用IMapper接口的控制器都将在创建时通过Mapper类。

此外,只知道瞬态之外还有其他寿命。例如Singleton,那里只能有该类的1个实例。

本文链接:https://www.f2er.com/3113892.html

大家都在问