如何使用Unity有条件地注册和解析通用类型

时间:2014-09-07 03:08:26

标签: c# asp.net-mvc-4 unity-container

我的主要模型类是" RoleMaster和" UserMaster"

public  class RoleMaster
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}

public  class UserMaster
{
    public int UserId { get; set; }
    public string UserName { get; set; }
}

这是我的主要存储库接口

   public interface IRepository<in T> where T : class 
   {
       bool Add(T entity);
   }

为RoleMaster实现了类

public class RoleRepository : IRepository<RoleMaster>
    {

        public bool Add(RoleMaster entity)
        {
             //Add Logic
        }
}

为UserMaster实施了类

  public class UserRepository : IRepository<UserMaster>
        {
            public bool Add(UserMaster entity)
            {
              //Add Logic
            }
    }

现在我想实现

 container.RegisterType<(IRepository<T>)(new InjectionFactory(m =>
            {
                if (typeof(T) is RoleMaster)
                {
                    m.Resolve<RoleRepository>();
                }
                else if (typeof(T) is UserMaster)
                {
                    m.Resolve<UserRepository>();
                }
                return m;
            }));

是否可以使用Unity?

进行这种条件Resolve的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您应该使用unity

明确注册它们
container.RegisterType<IRepository<RoleMaster>, RoleRepository>();
container.RegisterType<IRepository<UserMaster>, UserRepository>();

答案 1 :(得分:4)

我建议你使用通用存储库模式或为每个存储库创建一个新接口。或两者的结合,但这可能会让人感到困惑。

使用通用存储库(有很多示例),您只需要调用容器来注册开放的泛型类型,因为IRepsitory<T>接口只有一个实现...

container.RegisterType(typeof(IRepository<>), typeof(GenericRepository<>));

但是,如果您计划在每个存储库上添加自定义方法,则可能需要在该实体类型的自定义存储库接口上定义的那些方法。然后,最好在自定义存储库接口而不是通用接口上进行注册...

container.RegisterType<IRepositoryRole, RoleRepository>();

public interface IRepositoryRole : IRepository<RoleMaster> 
{
    public void DoCustomRoleWork(...) { ... }
}