在3层asp.net MVC应用程序依赖注入 [英] Dependency Injection in a 3 layer asp.net mvc application

查看:128
本文介绍了在3层asp.net MVC应用程序依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3层的应用和层是:

I have a 3 layer application and the layers are:


  • 网页:presentation层(ASP.NET MVC) - >只看到BLL

  • BLL:业务逻辑层 - >只看到DAL

  • DAL:数据访问层

所以网​​站层不知道我的 DAL 层东西。我有库接口和具体类在我的 DAL ,这是在 BLL 层中的业务逻辑类中使用。现在的问题是,为了分离 DAL BLL ,我怎么设置Ninject注入我的仓库实现的 BLL 图层?

So the Web layer doesn't know anything about my DAL layer. I have repository interfaces and concrete classes in my DAL, which are used in BLL layer in business logic classes. The question is, in order to decouple DAL and BLL, how do I setup Ninject to inject my repository implementations to the BLL layer?

同样的问题是网​​站层和 BLL 层,我对<$ C $接口和实现C> BLL 我在网​​站层使用它们,我应该如何设置Niject这个?

The same question is for Web layer and BLL layer, I have interfaces and implementations on BLL which I use them in Web layer, how should I setup Niject for this?

推荐答案

的想法是,你定义为你的DAL和BLL接口。然后你把这样的接口作为构造函数的参数的实例。示例

The idea is that you define interfaces for your DAL and BLL. You then take an instance of such an interface as a constructor parameter. Example

interface IDatabase
{
    // Methods here
}

您BLL类:

public class Bll
{
    IDatabase _db;
    public Bll(IDatabase db)
    {
        _db = db;
    }

    public void SomeMethod()
    {
        // Use db here
    }
}

然后在你的作文根(Web应用程序),您使用的内核配置这些依赖关系:

Then in your composition root (in the web application) you use the kernel to configure these dependencies:

 kernel.Bind<IDatabase>().To<ConcreteDatabase();

您需要从控制器同样的事情你BLL,但它的工作原理是一样的。

You need the same thing from your controllers to your BLL, but it works the same way.

除此之外,我认为你依赖性没有正确设置。一般来说,你不希望这些垂直的依赖关系。你的目标应该是一个平坦的层次。我写了一篇博客文章中针对此:的http://www.kenneth-truyers.net/2013/05/12/the-n-layer-myth-and-basic-dependency-injection/

Apart from that, I think your dependencies are not correctly set up. In general you don't want these vertical dependencies. You should aim for a flatter hierarchy. I wrote a blog post about this: http://www.kenneth-truyers.net/2013/05/12/the-n-layer-myth-and-basic-dependency-injection/

在我的博客文章中,我解释一下这个问题是这样的层次结构以及如何避免它的东西。除此之外,它精确地描述了你的问题:ASP.NET MVC,BLL,DLL和Ninject绑在一起

In my blog post I explain what the problem is with such a hierarchy and how you can avoid it. Apart from that, it describes exactly your problem: ASP.NET MVC, BLL, DLL and Ninject to tie it together.

这篇关于在3层asp.net MVC应用程序依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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