如何在MVC中注入带构造函数参数的类?

时间:2017-05-01 00:43:12

标签: c# dependency-injection asp.net-core-mvc

如果已经回答,请道歉。我已经搜索过,无法找到解决方案。

如何在#5的MVC中注入一个带构造函数参数的类?它甚至可能吗?

对于下面的代码,它会出错,因为它无法构造被注入的MyHelper1,因为它缺少sqlContext参数。

以下是我的(简化)对象:

// 1. HELPER CLASS TO INJECT
public class MyHelper1 : HelperBase, IHelper
{
    public MyHelper1(IHelperSqlContext sqlContext) : HelperBase(sqlContext)
    public override string HelperTag { get; } = "HELPER1";
    . . .
}

// 2. BASE HELPER
public abstract class HelperBase 
{
    private IHelperSqlContext _sqlContext;
    abstract public string HelperTag { get; }
    public HelperBase(IHelperSqlContext sqlContext)
    {
        _sqlContext = sqlContext;
    }
    public List<HelperRecords> GetRecords(Id id)
    {
        return _sqlContext.GetRecords(id);
    }
    . . . 
}

// 3. INTERFACE
public interface IHelper
{
    . . . 

}

// 4. CONTROLLER
public class MyController : Controller
{
    IHelper _myHelper
    public MyController(IHelper myHelper)
    {
         _myHelper = myHelper;
    }

    public IActionResult Index(Id id)
    {
        var model = new MyViewModel();
        model.MyRecords = _myHelper.GetRecords(id);
        return View(model);
    }
}

// 5. STARTUP - INJECT PART
public class Startup
{
    . . .
    public void ConfigureServices(IServiceCollection services)
    {
        . . . 
        // How to pass MyHelper1 class with IHelperSqlContext here???
        services.AddTransient<IHelper, MyHelper1>();
    }  
}

感谢任何帮助。提前谢谢。

2 个答案:

答案 0 :(得分:0)

是的,您需要做的就是在Startup类的ConfigureServices方法中注册所有依赖项(也就是依赖项依赖项)。

所以在这种情况下你需要添加这样一行。

services.AddTransient<IHelperSqlContext, MyHelperSqlContext>();

您可以在Microsoft文档中获取有关依赖项注入的更多信息here

答案 1 :(得分:0)

所有依赖项都需要在DI容器中注册,以便它知道如何解决它及其依赖项。

以下假设抽象是作为DbContext派生类实现的。

public class Startup {
    //. . .

    public void ConfigureServices(IServiceCollection services) {

        //. . . 

        //Register your context with dependency injection
        services.AddDbContext<HelperSqlDbContext>(options =>    
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
        );
        //register the context with its abstraction
        service.AddScoped<IHelperSqlContext, HelperSqlDbContext>()

        services.AddTransient<IHelper, MyHelper1>();
    }  
}
相关问题