Confused in Dependency Injection
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 replac开发者_JAVA百科e 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:
kernel
.Bind<IDbAccessLayer>()
.To<DAL>()
.WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");
And instead of hardcoding the connection string in your Global.asax
you could read it from your web.config using:
ConfigurationManager.ConnectionStrings["CNName"].ConnectionString
and now your DAL class could take the connection string as parameter:
public class DAL: IDbAccessLayer
{
private readonly string _connectionString;
public DAL(string connectionString)
{
_connectionString = connectionString;
}
... implementation of the IDbAccessLayer methods
}
Create a parameter-less constructor that calls the one-parameter constructor with a default connection string.
public DAL() : this("default connection string") {
}
public DAL(string connectionString) {
// do something with connection string
}
I've not worked with ninject, just a bit with Unity. But all the IOC containers seem to gravitate towards you making your own factory class that takes your stateful parameters (your connection string), which returns your real object. For example, if you had a Person class which requires a "name" and "age" for the constructor, then you must make a factory which would interact with Unity rather like this:
IPerson foo = container.Resolve<IPersonFactory>().Create("George", 25);
This is one of the things I don't like about IOC containers, but it's generally where it goes...
Just stupid idea having no knowledge of ninject:
kernel.Bind<IMyConnectionString>().To<MyConnectionString>();
And to your DAL constructor accepting IMyConnectionString
精彩评论