给段伪代码来说明问题:用的是NHibernate和Nunit
1)Infrastructure
public class Repository<T>:IRepository<T> where T:class
{
private ISession m_session;
#region IRepository<T> Members
public Repository(ISession session)
{
this.m_session = session;
}
public IList<T> findByHQL(string hql)
{
return this.m_session.CreateQuery(hql).List<T>();
}
public void add(T entity)
{
throw new NotImplementedException();
}
public void Save(T entity)
{
this.m_session.Save(entity);
this.m_session.Flush();
}
public void Delete(T entity)
{
throw new NotImplementedException();
}
#endregion
}
2)Service
public class UserService
{
private IRepository<User> m_repository;
public UserService(IRepository<User> repository)
{
this.m_repository = repository;
}
public string getNameByID(int id)
{
return m_repository.findByHQL("from User as c where c.UserID='" + id + "'")[0].UserName;
}
}
[TestFixtureSetUp]
public void init()
{
this.m_helper = new NHibernateHelper();
this.m_session = this.m_helper.getSession();
this.m_service = new UserService(new Repository<User>(this.m_session));
}
可以看出目标Service要注入一个Repository<User>来实现持久化,类似这样的注入应该如何用IOC容器配置注入规则?可否给点伪代码来看看?瓶颈在这里很久。
重点在于泛型类的信息使用配置化。
可以保存它的AssemblyQualifiedName。
//单元测试中:
string typeName = "";//配置
var tType = Type.GetType(typeName);
var interfaceType = typeof(IRepository<>).MakeGenericType(tType);
var repository = Unity.Instance.Resolve(interfaceType) as IRepository<User>;
this.m_service = new UserService(repository);