UnityContainer - how register/resolve with dependency chaining
I have an MVC app that has Controller
that takes a IDomainService
.
The DomainService
class constructor takes an IRepository
and the Repository
class constructor requires a connection string.
I have something like this:
string connectionString = ConfigurationManager
.ConnectionStrings["ApplicationServices"].ConnectionString;
c.RegisterInstance("ConnectionString", connectionString);
c.RegisterType<IDepartmentRepository, DepartmentRepository>(
"DepartmentRepository",
new InjectionConstructor(connectionString));
c.RegisterType<IDepartmentDom开发者_运维技巧ainService, DepartmentService>(
new InjectionConstructor(
new ResolvedParameter<IDepartmentRepository>(
"DepartmentRepository")));
However, this doesn't work.
Am I do something wrong? I have no problem with the repository injection, but I can't get my domain service injected (with the repository) to work.
Thanks.
I usually add a small class for this:
public class AppConfigConnectionFactory : IConnectionFactory
{
public IDbConnection Create()
{
return new SqlConnection(ConfigurationManager
.ConnectionStrings["ApplicationServices"].ConnectionString);
}
}
c.RegisterType<IConnectionFactory, AppConfigConnectionFactory>();
c.RegisterType<IDepartmentRepository, DepartmentRepository>();
Do not depend on strings if you do not have to. And you'll also avoid some code duplication in each repository with this solution.
精彩评论