IRepository, IService, Unity in an ASP.NET MVC App

2019-09-06 08:04发布

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条回答
狗以群分
2楼-- · 2019-09-06 08:48

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>();
查看更多
登录 后发表回答