如何进行 ASP.NET 依赖注入

发布于 2024-10-30 18:44:41 字数 1504 浏览 3 评论 0原文

所以在高层次上我理解依赖注入的概念。我们公司希望采用这种做法,我认为这是一个好主意,但我需要更多信息并有几个问题。

  1. 什么是好的或最流行的依赖注入容器?我听说过 ninject,它与 .NET 4 Webforms 配合得很好吗? Microsoft 是否有可能更好的专有 DI 容器?

  2. 我们的应用程序结构是这样的:

    • 解决方案
      • UI 项目(ASP.NET Web 应用程序)
      • 业务层(类库)
      • 数据访问层(类库)
    • 数据访问层包含用于访问数据的存储库类。这些存储库位于业务层与之交互的接口下。
    • 业务层具有包含常见功能的“控制器”类(不要与 MVC 控制器混淆)。

下面是我们业务层的一个示例控制器:

public class OrderController
{
    IOrderRepository _orderRepository;

    public OrderController(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public List<string> GetFilters()
    {
        // Return list of filters.
    }

    public List<Order> GetFilteredOrders(string filter)
    {
        switch (filter)
        {
            case "Newest":
                return // Get orders sorted by newest first.
            case "Oldest":
                return // Get orders sorted by oldest first.
            default:
                return // etc etc etc
        }
    }
}

如您所见,它采用了 IOrderRepository 的注入实例,以便于进行单元测试。 OrderController 当前在需要使用它的相应页面的代码后面进行实例化。我们不想在实例化 OrderController每个位置创建一个新的 IOrderRepository,这就是我们想要使用 DI 的地方。

实现这一点的最佳方法是什么? DI 容器何时接管并注入 IOrderRepository 实例?是否会有某种工厂,以便我可以执行 OrderController _orderController = OrderControllerFactory.Create() 或类似的操作?我有点迷失了。

如果我需要澄清一些事情,请告诉我。谢谢。

So on a high level I understand the concept of dependency injection. Our company wants to adopt this practice and I think it is a good idea, but I need some more information and have a few questions.

  1. What is a good or most popular dependency injection container? I have heard of ninject, does that work well with .NET 4 Webforms? Does Microsoft have a proprietary DI Container that might be better?

  2. Our application structure is like this:

    • Solution
      • UI Project (ASP.NET Web App)
      • Business Layer (Class Library)
      • Data Access Layer (Class Library)
    • The data access layer contains repository classes for accessing data. These repositories sit under interfaces that the business layer interacts with.
    • The business layer has "controller" classes (not to be confused with MVC controllers) that contain common functionality.

Here is an example controller from our business layer:

public class OrderController
{
    IOrderRepository _orderRepository;

    public OrderController(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public List<string> GetFilters()
    {
        // Return list of filters.
    }

    public List<Order> GetFilteredOrders(string filter)
    {
        switch (filter)
        {
            case "Newest":
                return // Get orders sorted by newest first.
            case "Oldest":
                return // Get orders sorted by oldest first.
            default:
                return // etc etc etc
        }
    }
}

As you can see this takes an injected instance of IOrderRepository for easy unit testability. OrderController is currently instantiated in the code behind of the appropriate page that needs to use it. We don't want to create a new IOrderRepository in every place where we instantiate OrderController, this is where we want to use DI.

What is the best way to implement this? At what point does the DI Container take over and inject an instance of IOrderRepository? Would there be some kind of factory so I could do OrderController _orderController = OrderControllerFactory.Create() or something like that? I'm kind of lost.

Let me know if I need to clarify something. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

做个ˇ局外人 2024-11-06 18:44:41

我的偏好是坚持使用 Microsoft 堆栈并使用 Unity;尽管我有同事在项目中使用 Ninject 并且喜欢它。

以下是我在 Web 应用程序中执行此操作的方法(MVC 应用程序稍微复杂一些):

using Microsoft.Practices.Unity;

public class OrderController
{
    IOrderRepository _orderRepository;

    [InjectionConstructor]
    public OrderController(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public List<string> GetFilters()
    {
        // Return list of filters.
    }

    public List<Order> GetFilteredOrders(string filter)
    {
        switch (filter)
        {
            case "Newest":
                return // Get orders sorted by newest first.
            case "Oldest":
                return // Get orders sorted by oldest first.
            default:
                return // etc etc etc
        }
    }
}


/// 
/// From Global.asax.cs

using Microsoft.Practices.Unity;

private void ConfigureUnity()
{        
    // Create UnityContainer           
    IUnityContainer container = new UnityContainer()
    .RegisterInstance(new OrderController())
    .RegisterType<IOrderRepository, OrderRepository>();

    // Set container for use in Web Forms
    WebUnityContainer.Container = container;
}       

///
/// Creating the OrderController from your Web UI

public OrderController CreateOrderController()
{
    return WebUnityContainer.Container.Resolve<OrderController>();
}

///
/// Shared static class for the Unity container

using Microsoft.Practices.Unity;

namespace MyCompany.MyApplication.Web
{
    public static class WebUnityContainer
    {
        public static IUnityContainer Container { get; set; }
    }
}

My preference is to stick with the Microsoft stack and use Unity; although I have colleagues who use Ninject on projects and love it.

Here is how I do this exact thing in a web application (MVC apps are just slightly more involved):

using Microsoft.Practices.Unity;

public class OrderController
{
    IOrderRepository _orderRepository;

    [InjectionConstructor]
    public OrderController(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public List<string> GetFilters()
    {
        // Return list of filters.
    }

    public List<Order> GetFilteredOrders(string filter)
    {
        switch (filter)
        {
            case "Newest":
                return // Get orders sorted by newest first.
            case "Oldest":
                return // Get orders sorted by oldest first.
            default:
                return // etc etc etc
        }
    }
}


/// 
/// From Global.asax.cs

using Microsoft.Practices.Unity;

private void ConfigureUnity()
{        
    // Create UnityContainer           
    IUnityContainer container = new UnityContainer()
    .RegisterInstance(new OrderController())
    .RegisterType<IOrderRepository, OrderRepository>();

    // Set container for use in Web Forms
    WebUnityContainer.Container = container;
}       

///
/// Creating the OrderController from your Web UI

public OrderController CreateOrderController()
{
    return WebUnityContainer.Container.Resolve<OrderController>();
}

///
/// Shared static class for the Unity container

using Microsoft.Practices.Unity;

namespace MyCompany.MyApplication.Web
{
    public static class WebUnityContainer
    {
        public static IUnityContainer Container { get; set; }
    }
}
悟红尘 2024-11-06 18:44:41

此处使用结构图

http://structuralmap.net/structuralmap/

在结构图中,它是这样的:

ObjectFactory.GetInstance(Of OrderController)

关于结构图的好链接:

http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuralmap.aspx

哪个 .NET依赖注入框架值得研究吗?

开源应用程序:

使用 Unity,另一个很好的依赖注入框架:http: //kigg.codeplex.com/

1~2年前我也有同样的问题,从那时起我就一直在使用StructureMap,我对它很满意,但我知道像Ninject这样的其他框架和StructureMap一样好。

Using Structure Map here.

http://structuremap.net/structuremap/

In Structure Map it's like this:

ObjectFactory.GetInstance(Of OrderController)

Nice links about Structure Map:

http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx

Which .NET Dependency Injection frameworks are worth looking into?

Open source app:

Uses Unity, another good dependency injection framework: http://kigg.codeplex.com/

I had the same question 1~2 years ago, and I have been using StructureMap since then and I'm happy with it but I know other frameworks like Ninject are as good as StructureMap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文