I am new to MVC and dependency injection. Please help me to understand how that should work. I use Ninject. Here is my code:
in 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();
}
IDbAccessLayer implementation is very simple:
public interface IDbAccessLayer
{
DataContext Data { get; }
IEnumerable<User> GetUsers();
}
now in a Controller I need to create a constructor that gets IDbAccessLayer param. And that just works.
Now I don’t know how to pass a connection string to DAL. if I try to replace DAL’s constructor with something that accepts a parameter, it doesn’t work. Throws an exception with message No parameterless constructor defined for this object
You could specify constructor parameters:
And instead of hardcoding the connection string in your
Global.asaxyou could read it from your web.config using:and now your DAL class could take the connection string as parameter: