IRepository, IService, Unity in an ASP.NET MVC Application, reference question

可紊 提交于 2019-12-24 18:53:22

问题


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):

  • Business Objects – Folder
    • DomainModel (Class Lib prj.) – Entity Framework 2 POCO entities
  • Data Layer – Folder
    • DataAccess (Class Lib prj.) – EF2 EDMX
    • Repository (Class Lib prj.) – IRepository interface & repository concrete implementations
  • Presentation Layer – folder
    • WebUI – MVC Project
  • Service Layer
    • Service (Class Lib prj.) – IService interface and service (façade pattern) concrete implementations

All project reference the DomainModel project.

Repository references the DataAccess project.

Service Layer references the Repository project.

WebUI references the Service project & the Unity assemblies.

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?

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. Move the IRepository Interfaces into the DomainModel and add the Unity.RegisterType<> calls for the IRepository
  2. Set up Unity configuration in the Web.config

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


回答1:


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

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.
    }
}

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

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


来源:https://stackoverflow.com/questions/3998559/irepository-iservice-unity-in-an-asp-net-mvc-application-reference-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!