Vaguely dependent on injection

I am new to MVC and dependency injection. Please help me understand how this should work. I am using Ninject. Here is my code:

in the Global.asax file:

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();
    }

The implementation of IDbAccessLayer is very simple:

public interface IDbAccessLayer
{
  DataContext Data { get; }
  IEnumerable<User> GetUsers();
}

Now in the controller I need to create a constructor that receives the IDbAccessLayer parameter. And it only works.

Now I do not know how to pass the DAL connection string. if I try to replace the DAL constructor with something that takes a parameter, this will not work. Throws an exception with the message Without constructor without parameters for this object

+3
source share
4 answers

You can specify constructor options:

kernel
    .Bind<IDbAccessLayer>()
    .To<DAL>()
    .WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");

, Global.asax, web.config, :

ConfigurationManager.ConnectionStrings["CNName"].ConnectionString

DAL :

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

    ... implementation of the IDbAccessLayer methods
}
+5

, .

public DAL() : this("default connection string") {

}

public DAL(string connectionString) {
    // do something with connection string
}
+1

ninject, Unity. , , , factory, ( ), . , Person, , factory, Unity, :

IPerson foo = container.Resolve<IPersonFactory>().Create("George", 25);

, IOC, ...

0

, :

kernel.Bind<IMyConnectionString>().To<MyConnectionString>();

DAL, IMyConnectionString

0
source

All Articles