首页 新闻 搜索 专区 学院

IOC如何注入泛型IRepository<T>类型对象?有伪代码说明问题

0
[已解决问题] 解决于 2010-10-29 16:38

给段伪代码来说明问题:用的是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容器配置注入规则?可否给点伪代码来看看?瓶颈在这里很久。

bugfly的主页 bugfly | 初学一级 | 园豆:10
提问于:2010-10-28 16:39
< >
分享
最佳答案
0

重点在于泛型类的信息使用配置化。

可以保存它的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);

BloodyAngel | 菜鸟二级 |园豆:230 | 2010-10-28 21:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册