在依赖注入中感到困惑

iLe*_*ing 3 c# dependency-injection ninject asp.net-mvc-3

我是MVC和依赖注入的新手.请帮助我理解它应该如何工作.我用Ninject.这是我的代码:

在Global.asax文件中:

private void RegisterDependencyResolver()
    {
        var kernel = new StandardKernel();
        kernel.Bind<IDbAccessLayer>().To<DAL>(); 
        // DAL - is a Data Access Layer that comes from separated class library 
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

protected void Application_Start()
    {
        RegisterDependencyResolver();
    }
Run Code Online (Sandbox Code Playgroud)

IDbAccessLayer实现非常简单:

public interface IDbAccessLayer
{
  DataContext Data { get; }
  IEnumerable<User> GetUsers();
}
Run Code Online (Sandbox Code Playgroud)

现在在Controller中我需要创建一个获取IDbAccessLayer参数的构造函数.这才有效.

现在我不知道如何将连接字符串传递给DAL.如果我尝试用接受参数的东西替换DAL的构造函数,它就不起作用.使用消息引发异常没有为此对象定义无参数构造函数

Dar*_*rov 5

您可以指定构造函数参数:

kernel
    .Bind<IDbAccessLayer>()
    .To<DAL>()
    .WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");
Run Code Online (Sandbox Code Playgroud)

而不是硬编码您的连接字符串,您Global.asax可以使用以下命令从web.config中读取它:

ConfigurationManager.ConnectionStrings["CNName"].ConnectionString
Run Code Online (Sandbox Code Playgroud)

现在您的DAL类可以将连接字符串作为参数:

public class DAL: IDbAccessLayer
{
    private readonly string _connectionString;
    public DAL(string connectionString) 
    {
        _connectionString = connectionString;
    } 

    ... implementation of the IDbAccessLayer methods
}
Run Code Online (Sandbox Code Playgroud)