ASP.NET MVC 应用程序中的 IRepository、IService、Unity,参考问题 [英] IRepository, IService, Unity in an ASP.NET MVC Application, reference question

查看:63
本文介绍了ASP.NET MVC 应用程序中的 IRepository、IService、Unity,参考问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Unity 的新手,但这个问题对 IoC 来说更通用,而且我对整体实现 IoC 还很陌生.我有这个项目结构的 VS2010 解决方案(稍微简化):

I'm new to Unity, but this question is more generic to IoC, and I’m pretty new to implementing IoC as a whole. I have VS2010 solution with this project structure (simplified slightly):

  • 业务对象 – 文件夹
    • DomainModel (Class Lib prj.) – Entity Framework 2 POCO 实体
    • 数据访问(类库项目)——EF2 EDMX
    • Repository (Class Lib prj.) – IRepository 接口 &存储库具体实现
    • WebUI – MVC 项目
    • Service (Class Lib prj.) – IService 接口和服务(外观模式)具体实现

    所有项目都引用了 DomainModel 项目.

    All project reference the DomainModel project.

    存储库引用了 DataAccess 项目.

    Repository references the DataAccess project.

    服务层引用 Repository 项目.

    Service Layer references the Repository project.

    WebUI 引用了 Service 项目 &Unity 程序集.

    WebUI references the Service project & the Unity assemblies.

    我已将 Unity 配置为在 WebUI 中正确注入我的所有服务类型(通过自定义 UnityControllerFactory.cs 进行的 global.asax).但是如何在服务层配置Unity来注入repository对象呢?

    I have Unity configured to inject all my service types correctly in the WebUI (global.asax via a custom UnityControllerFactory.cs). But how do I configure Unity in the service layer to inject the repository objects?

    我不想从 WebUI 引用 Repository 项目以确保在开发过程中没有捷径和绕过服务层.

    I DON’T want to reference the Repository project from the WebUI to ensure during development no one shortcuts and bypass the Service layer.

    我有几个想法(不确定它是否会解决它):

    Couple Ideas I have (not sure if it will solve it):

    1. 将 IRepository 接口移动到 DomainModel 并添加 Unity.RegisterType<> 调用 IRepository
    2. 在 Web.config 中设置 Unity 配置

    任何方向都将不胜感激,特别是如何为服务层/存储库配置 Unity,但总体上也与项目有关.

    Any direction would be greatly appreciated, specifically to how to configure Unity for the service layer / Repository, but also in general about the project.

    推荐答案

    在 Service 项目中添加某种引导程序.然后在 WebUI 中引用引导程序.

    Add a bootstrapper of some sort in the Service project. Then reference the bootstrapper in the WebUI.

    一种方法是编写一个小的 Unity 扩展.像这样:

    One way to do this would be to write a small Unity extension. Something like this:

    public class ServiceLayerBootstrap : UnityContainerExtension
    {
        protected override void Initialize()
        {
            Container.RegisterType<IRepository, WhateverRepositoryImplementation>();
            // etc.
        }
    }
    

    然后,在您创建容器并对其进行初始化的 Web 项目中,执行以下操作:

    Then, in the web project where you create the container and initialize it, do this:

    var container = new UnityContainer()
        .AddNewExtension<ServiceLayerBootstrap>();
    

    这篇关于ASP.NET MVC 应用程序中的 IRepository、IService、Unity,参考问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆