IoC的存储库模式 - 如何正确使用?

时间:2013-01-22 08:04:06

标签: asp.net-mvc repository unity-container ioc-container

我是一个独立的开发人员,Pluralsight是我帮助我理解Repository和IoC之类的东西,我正在学习。 但是我发现这种模式很难使用。

所以我使用Unity IoC,并关注ModelContainer类;

public static class ModelContainer
{
    private static IUnityContainer instance;

    static ModelContainer()
    {
        instance = new UnityContainer();
    }

    public static IUnityContainer Instance
    {
        get
        {
            instance.RegisterType<ISCD_CallDiaryRepository, SCD_CallDiaryRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<ICompanyRepository, CompanyRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<ISubcontractorRepository, SubcontractorRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<ITradeRepository, TradeRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<IEmployeeRepository, EmployeeRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<ISubcontractorTradeRepository, SubcontractorTradeRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<ICountyRepository, CountyRepository>(new HierarchicalLifetimeManager());
            instance.RegisterType<IAddressLineRepository, AddressLineRepository>(new HierarchicalLifetimeManager());
            return instance;
        }
    }
}

允许我在我的控制器的构造函数中实例化存储库类;

public SubcontractorController(
        ISubcontractorRepository subcontractorRepository,
        ISubcontractorTradeRepository subcontractorTradeRepository, 
        ICompanyRepository companyRepository, 
        ISCD_CallDiaryRepository scdCallDiaryRepository,
        ITradeRepository tradeRepository,
        IAddressLineRepository addressLineRepository)
    {
        this.SubcontractorRepository = subcontractorRepository;
        this.SubcontractorTradeRepository = subcontractorTradeRepository;
        this.CompanyRepository = companyRepository;
        this.ScdCallDiaryRepository = scdCallDiaryRepository;
        this.TradeRepository = tradeRepository;
        this.AddressLineRepository = addressLineRepository;
    }

我觉得这个设置很尴尬的是,如果我想在这些存储库类中使用CRUD功能,我必须在控制器中执行功能,或者将我作为参数创建的存储库实例传递给模型类方法。我选择后者,控制器不是要做太多,但我不能继续传递存储库参数。

我错过了什么?

3 个答案:

答案 0 :(得分:5)

在提供的示例中,SubcontractorController控制器具有六个依赖,这通常意味着控制器一次尝试做太多,并且可能违反单一责任原则。改善情况至少有三种方法:

  • 而不是将存储库注入控制器,并将存储库实例作为参数传递到< em>模型类方法,你可以refactor to Aggregate Services,即将模型方法和依赖关系结合在单个实体中。这也将解决构造函数过度注入问题。
  • 将存储库的工厂注入控制器,然后使用此工厂解决依赖关系
  • 自己注入模型,并将存储库作为其依赖项。

答案 1 :(得分:5)

我将MVC应用程序分成几个不同的项目。

  • AppName.Configuration:处理应用程序的任何配置(即拉入web.config / app设置等)
  • AppName.Data:这是执行所有数据库访问的数据层(没有业务逻辑)。 DBML / EDMX就在这里,我的存储库类也在这里。
  • AppName.Models:这是我为MVC定义的所有ViewModel,以及整个应用程序所需的其他模型对象。
  • AppName.Services:这是我的业务层,所有内容都必须通过这里才能到达数据层或表示层。 ViewModel是从数据库对象构造的,数据验证在这里发生,等等。
  • AppName.Web:这将是MVC应用程序。 AppName.Data.Test:数据应用程序的单元测试
  • AppName.Services.Test:服务的单元测试
  • AppName.Web.Test:MVC控制器的单元测试
  • AppName.Web.UI.Test:Web用户界面的单元测试(使用WATIN)

我还有一组打包到NuGet包中的类,我可以在需要时添加到我的应用程序中,即(对于此示例):

  • CompanyName.Data:数据层逻辑的公共库
  • CompanyName.MVC:ASP.NET MVC集成的公共库
  • CompanyName.Utilities:其他实用程序的公共库

除了从服务层获取视图模型以发送到视图,然后从视图发布后接收数据并将其发送到服务层进行验证并保存回存储库,我的控制器什么都不做。

这是一个基本的例子:

这是将在此示例中使用的视图模型:

public class CreateFocusViewModel
{
    public int CareerPlanningFormID { get; set; }

    public int PerformanceYear { get; set; }

    public IList<FocusModel> Focuses { get; set; }

    public string ResultsMeasuresFocusComments { get; set; }

    public byte MaximumFocusesAllowed { get; set; }
}

public class FocusModel
{
    public int FocusID { get; set; }

    public string FocusText { get; set; }

    public bool IsPendingDeletion { get; set; }
}

使用GET和POST操作方法的示例控制器:

public class CPFController : Controller
{
    private readonly ICareerPlanningFormService careerPlanningFormService;

    public CPFController(ICareerPlanningFormService careerPlanningFormService)
    {
        this.careerPlanningFormService = careerPlanningFormService;
    }

    [HttpGet]
    public ViewResult CreateFocus(int careerPlanningFormID)
    {
        var model = this.careerPlanningFormService.BuildCreateFocusViewModel(careerPlanningFormID);
        return this.View(model);
    }

    [HttpPost]
    public ActionResult CreateFocus(int careerPlanningFormID, string button)
    {
        var model = this.careerPlanningFormService.BuildCreateFocusViewModel(careerPlanningFormID);
        this.TryUpdateModel(model);

        switch (button)
        {
            case ButtonSubmitValues.Next:
            case ButtonSubmitValues.Save:
            case ButtonSubmitValues.SaveAndClose:
                {
                    if (this.ModelState.IsValid)
                    {
                        try
                        {
                            this.careerPlanningFormService.SaveFocusData(model);
                        }
                        catch (ModelStateException<CreateFocusViewModel> mse)
                        {
                            mse.ApplyTo(this.ModelState);
                        }
                    }

                    if (!this.ModelState.IsValid)
                    {
                        this.ShowErrorMessage(Resources.ErrorMsg_WEB_ValidationSummaryTitle);
                        return this.View(model);
                    }

                    break;
                }

            default:
                throw new InvalidOperationException(string.Format(Resources.ErrorMsg_WEB_InvalidButton, button));
        }

        switch (button)
        {
            case ButtonSubmitValues.Next:
                return this.RedirectToActionFor<CPFController>(c => c.SelectCompetencies(model.CareerPlanningFormID));

            case ButtonSubmitValues.Save:
                this.ShowSuccessMessage(Resources.Msg_WEB_NotifyBarSuccessGeneral);
                return this.RedirectToActionFor<CPFController>(c => c.CreateFocus(model.CareerPlanningFormID));

            case ButtonSubmitValues.SaveAndClose:
            default:
                return this.RedirectToActionFor<UtilityController>(c => c.CloseWindow());
        }
    }
}

构建ViewModel并验证/保存数据的服务层:

public class CareerPlanningFormService : ICareerPlanningFormService
{
    private readonly IAppNameRepository repository;
    private readonly IPrincipal currentUser;

    public CareerPlanningFormService(IAppNameRepository repository, IPrincipal currentUser)
    {
        this.repository = repository;
        this.currentUser = currentUser;
    }

    public CreateFocusViewModel BuildCreateFocusViewModel(int careerPlanningFormID)
    {
        var cpf = this.repository.GetCareerPlanningFormByID(careerPlanningFormID);

        // create the model using cpf
        var model = new CreateFocusViewModel
        {
            CareerPlanningFormID = cpf.CareerPlanningFormID,
            PerformanceYear = cpf.PerformanceYearID,
            ResultsMeasuresFocusComments = cpf.ResultsMeasuresFocusComments,
            MaximumFocusesAllowed = cpf.PerformanceYear.MaximumCareerPlanningFormFocusesAllowed
            // etc., etc...
        };

        return model;
    }

    public void SaveFocusData(CreateFocusViewModel model)
    {
        // validate the model
        this.ValidateCreateFocusViewModel(model);

        // get the current state of the CPF
        var cpf = this.repository.GetCareerPlanningFormByID(model.CareerPlanningFormID);

        // bunch of code saving focus data here...

        // update the ResultsMeasuresFocusComments
        cpf.ResultsMeasuresFocusComments = string.IsNullOrWhiteSpace(model.ResultsMeasuresFocusComments) ? null : model.ResultsMeasuresFocusComments.Trim();

        // commit the changes
        this.repository.Commit();
    }

    private void ValidateCreateFocusViewModel(CreateFocusViewModel model)
    {
        var errors = new ModelStateException<CreateFocusViewModel>();

        {
            var focusesNotPendingDeletion = model.Focuses.Where(f => f.IsPendingDeletion == false);

            // verify that at least one of the focuses (not pending deletion) has a value
            {
                var validFocuses = focusesNotPendingDeletion.Where(f => !string.IsNullOrWhiteSpace(f.FocusText)).ToList();
                if (!validFocuses.Any())
                {
                    var index = model.Focuses.IndexOf(model.Focuses.Where(f => f.IsPendingDeletion == false).First());
                    errors.AddPropertyError(m => m.Focuses[index].FocusText, Resources.ErrorMsg_CPF_OneFocusRequired);
                }
            }

            // verify that each of the focuses (not pending deletion) length is <= 100
            {
                var focusesTooLong = focusesNotPendingDeletion.Where(f => f.FocusText != null && f.FocusText.Length > 100).ToList();
                if (focusesTooLong.Any())
                {
                    focusesTooLong.ToList().ForEach(f =>
                    {
                        var index = model.Focuses.IndexOf(f);
                        errors.AddPropertyError(m => m.Focuses[index].FocusText, Resources.ErrorMsg_CPF_FocusMaxLength);
                    });
                }
            }
        }

        errors.CheckAndThrow();
    }
}

存储库类:

public class AppNameRepository : QueryRepository, IAppNameRepository
{
    public AppNameRepository(IGenericRepository repository)
        : base(repository)
    {
    }

    public CareerPlanningForm GetCareerPlanningFormByID(int careerPlanningFormID)
    {
        return this.Repository.Get<CareerPlanningForm>().Where(cpf => cpf.CareerPlanningFormID == careerPlanningFormID).Single();
    }
}

存储库界面:

public interface IAppNameRepository : IRepository
{
    CareerPlanningForm GetCareerPlanningFormByID(int careerPlanningFormID);
}

CompanyName.Data公共库中的类:

public abstract class QueryRepository : IRepository
{
    protected readonly IGenericRepository Repository;

    protected QueryRepository(IGenericRepository repository)
    {
        this.Repository = repository;
    }

    public void Remove<T>(T item) where T : class
    {
        this.Repository.Remove(item);
    }

    public void Add<T>(T item) where T : class
    {
        this.Repository.Add(item);
    }

    public void Commit()
    {
        this.Repository.Commit();
    }

    public void Refresh(object entity)
    {
        this.Repository.Refresh(entity);
    }
}

public interface IGenericRepository : IRepository
{
    IQueryable<T> Get<T>() where T : class;
}

public interface IRepository
{
    void Remove<T>(T item) where T : class;
    void Add<T>(T item) where T : class;
    void Commit();
    void Refresh(object entity);
}

我有LinqToSQL和E.F.,这是LinqToSQL的设置:

internal sealed class LinqToSqlRepository : IGenericRepository
{
    private readonly DataContext dc;

    public LinqToSqlRepository(DataContext dc)
    {
        this.dc = dc;
    }

    public IQueryable<T> Get<T>() where T : class
    {
        return this.dc.GetTable<T>();
    }

    public void Remove<T>(T item) where T : class
    {
        this.dc.GetTable<T>().DeleteOnSubmit(item);
    }

    public void Add<T>(T item) where T : class
    {
        this.dc.GetTable<T>().InsertOnSubmit(item);
    }

    public void Commit()
    {
        this.dc.SubmitChanges();
    }

    public void Refresh(object entity)
    {
        this.dc.Refresh(RefreshMode.OverwriteCurrentValues, entity);
    }
}

这也在CompanyName.Data公共库中。它有注册LinqToSQL或EntityFramework

的方法
public static class UnityContainerExtensions
{
    public static IUnityContainer RegisterEntityFrameworkClasses<TDbContext>(this IUnityContainer container, string nameOrConnectionString) where TDbContext : DbContext
    {
        var constructor = typeof(TDbContext).GetConstructor(new Type[] { typeof(string) });
        container.RegisterType<DbContext>(new HierarchicalLifetimeManager(), new InjectionFactory(c => constructor.Invoke(new object[] { nameOrConnectionString })));
        container.RegisterType<IGenericRepository, EntityFrameworkRepository>();
        return container;
    }

    public static IUnityContainer RegisterLinqToSqlClasses<TDataContext>(this IUnityContainer container, string connectionString) where TDataContext : DataContext
    {
        var constructor = typeof(TDataContext).GetConstructor(new Type[] { typeof(string) });
        container.RegisterType<DataContext>(new HierarchicalLifetimeManager(), new InjectionFactory(c => constructor.Invoke(new object[] { connectionString })));
        container.RegisterType<IGenericRepository, LinqToSqlRepository>();
        return container;
    }
}

在CompanyName.Utilities库中:

public interface IUnityBootstrap
{
    IUnityContainer Configure(IUnityContainer container);
}

AppName.Data中的Unity引导

public class UnityBootstrap : IUnityBootstrap
{
    public IUnityContainer Configure(IUnityContainer container)
    {
        var config = container.Resolve<IAppNameConfiguration>();

        return container.RegisterLinqToSqlClasses<AppNameDataContext>(config.AppNameConnectionString)
                        .RegisterType<IAppNameRepository, AppNameRepository>();
    }
}

AppName.Services中的Unity引导

public class UnityBootstrap : IUnityBootstrap
{
    public IUnityContainer Configure(IUnityContainer container)
    {
        new CompanyName.Security.UnityBootstrap().Configure(container);
        new AppName.Data.UnityBootstrap().Configure(container);

        container.RegisterSecureServices<AuthorizationRulesEngine>(typeof(UnityBootstrap).Assembly);

        return container.RegisterType<ICareerPlanningFormService, CareerPlanningFormService>()
                        .RegisterType<IStaffService, StaffService>();
    }
}

AppName.Web中的Unity引导

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Standard MVC setup
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        // Application configuration 
        var container = new UnityContainer();
        new CompanyName.Mvc.UnityBootstrap().Configure(container);
        new AppName.Configuration.UnityBootstrap().Configure(container);
        new AppName.Data.UnityBootstrap().Configure(container);
        new AppName.Services.UnityBootstrap().Configure(container);

        // Default MVC model binder is pretty weak with collections
        ModelBinders.Binders.DefaultBinder = new DefaultGraphModelBinder();
    }

    protected void Application_Error()
    {
        HttpApplicationEventHandler.OnError(this.Context);
    }

    protected void Application_EndRequest()
    {
        HttpApplicationEventHandler.OnEndRequest(this.Context);
    }
}

答案 2 :(得分:1)

我在职业生涯的早期尝试过后者。它并没有结束。最终会出现意外的性能命中和大型模型对象。我认为控制器是你提到的逻辑的最佳位置。如果您担心同一类中的ui和业务问题,请将业务移至服务类。