ASP.NET MVC和服务层依赖注入

Žel*_*ber 1 .net asp.net-mvc dependency-injection unit-of-work service-layer

我有一些构造函数的问题,controller并且service被调用controller.

这是我的服务:

// model state dictionary for validation
private ModelStateDictionary _modelState;

// initialize UnitOfWork
private IUnitOfWork _unitOfWork;

public TownService(ModelStateDictionary modelState, IUnitOfWork unitOfWork)
{
    _modelState = modelState;
    _unitOfWork = unitOfWork;
}
Run Code Online (Sandbox Code Playgroud)

现在在我的控制器中我想创建新服务,传递控制器this.ModelState但不想添加UnitOfWork内部控制器.

像这样的东西:

private ITownService _townService;

public TownController()
{
    _townService = new TownService(this.ModelState, null);
}
Run Code Online (Sandbox Code Playgroud)

所以考虑的一切UnitOfWork都是在服务内部完成的.控制器只是传递它自己modelState,服务是创建新的服务UnitOfWork.

这可能也是好方法吗?我怎样才能做到这一点?或者我应该new UnitOfWork在控制器中添加而不是null参数?

因为我想尽可能地分离Core,DAL,Web,以便一切都发挥作用,并且在控制器和服务中添加UnitOfWork似乎是不好的方式......

谢谢.

hai*_*770 5

依赖注入:

首先,您必须正确掌握"依赖注入"的概念:

public TownController()
{
    _townService = new TownService(this.ModelState, null);
}
Run Code Online (Sandbox Code Playgroud)

TownController没有注入任何依赖,并且您_townService使用硬编码TownService实现进行实例化.

它应该看起来更像这样:

private ITownService _townService;

public TownController(ITownService townService)
{
    _townService = townService;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,ITownService实现正在注入控制器(使用其构造函数).

现在,如果你注入的dependency(ITownService)有自己的依赖项(IUnitOfWork),那并不意味着你的控制器也必须注入所有这些依赖项,因为当它ITownService被注入控制器时,它已经被初始化并且它的依赖已经被注射到它.

大多数人使用依赖注入框架来实现所有这些(以及更多),这是ASP.NET MVC 的简单Unity示例:

// some code omitted for brevity
internal static class DependencyResolvingConfig
{
    internal static IUnityContainer Configure()
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        return container;
    }

    internal static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<IUnitOfWork, UnitOfWork>();
        container.RegisterType<ITownService, TownService>();
    }
}
Run Code Online (Sandbox Code Playgroud)

这一行:

DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Run Code Online (Sandbox Code Playgroud)

告诉ASP.Net MVC,每当它实例化一个具有依赖性的新控制器时,它会要求UnityDependencyResolver提供实现,Unity将根据上面的配置执行此操作.

ModelStateDictionary:

另一个问题是您的服务层正在使用ModelStateDictionary:

a的概念ModelState(通常)是表示层关注的问题,用于验证和从UI(传统的HTML表单)返回/设置错误.

您应该检查并验证控制器中的模型状态,然后(通常只有在它有效时)调用服务层来执行实际操作.

此外,您必须System.Web.Mvc仅为了使用目的添加对Assembly 的引用ModelState(不建议这样做).