1

所以我在我的应用程序中使用 Autofac,看起来如下(从上到下的方法)。

该项目在 MVC 4 中,我添加了 AutoFac.MVC4 测试版。

  • Web App Client(Web 应用程序 - 表示层):namespace = AppBase.Web
  • Web App Core(例如各种 actionresults,...):namespace = AppBase.Web.Core
  • 服务(例如 AuthenticationService、MemberService、TaskService):命名空间 = AppBase.Service
  • 数据(包括存储库,...):命名空间 = AppBase.Data
  • 域(Code Fist 的 POCO 对象):命名空间 = AppBase.Domain

我将 Autofac 包含在我的 Web App Client 中,并带有以下初始化代码(目前):

public void RegisterContainersUsingAutofac()
    {
        var builder = new ContainerBuilder();
        builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
        builder.RegisterModelBinderProvider();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

Web App Client 引用核心、域和服务层。服务层引用数据层(对于存储库)。

我的数据层中有一个名为 iRepository 的接口,我所有的存储库都实现了这些

我想知道,我应该在我的“RegisterContainersUsingAutofac”方法中添加什么代码,以自动(以通用方式)添加所有存储库和服务,所以我不应该每次都自己添加它们。请记住,未引用数据层(我可以,但我认为不应该)。

PS。我过去使用过 Unity,但我喜欢 AutoFac 拥有的通用方法(在一个项目中,我有超过 +/-180 行添加存储库和服务,所以这是我不再想要的东西)。

4

2 回答 2

2

直到最近我还在使用 Unity.Mvc 并切换到 Autofac。我对 Unity.Mvc 的问题是,无缘无故,它会工作一分钟而不是下一分钟,它似乎非常不稳定。

Autofac 的使用和配置都很容易,自从我开始使用它以来,我没有遇到过任何问题。

我使用 WebActivator,所以我的大部分配置内容都在它们自己的类中作为引导程序对象,而不是在 Global.asax 文件中乱扔一堆代码。

下面是 Autofac 引导程序的 (VB.NET) 代码。您会看到,最初我在该文件中注册了每个服务对象和每个存储库对象,但现在它们已被注释掉,而我使用自动注册功能。

该项目正在使用 Mvc4。

#Region "Imports"

Imports System.Reflection
Imports Autofac
Imports Autofac.Integration.Mvc
Imports MyCompany.Data.Interfaces
Imports MyCompany.Data.Repositories
Imports MyCompany.Services
Imports MyCompany.Services.Interfaces
Imports MyCompany.Web.Mvc.Public.Bootstrap
Imports MyCompany.Web.Mvc.Public.Services

#End Region

#Region "Assembly Meta"

' This tells the app to run the "Start" method prior to running the App_Start method in Global.asax
<Assembly: WebActivator.PreApplicationStartMethod(GetType(AutofacDI), "Initialize")> 

#End Region

Namespace MyCompany.Web.Mvc.Public.Bootstrap

    ''' <summary>
    ''' Class to setup dependency injection and register types/services.
    ''' </summary>
    ''' <remarks></remarks>
    Public NotInheritable Class AutofacDI

        ''' <summary>
        ''' Method to register the Autofac dependency injection component.
        ''' </summary>
        ''' <remarks>
        ''' This line of code below could alternatively be placed in Global.asax App_Start(), doing
        ''' so in this manner ensures that this gets run "PreStart".
        ''' </remarks>
        Public Shared Sub Initialize()

            ' Create Unity dependency container.
            Dim dependencyContainer = BuildIocContainer()

            ' Set DI resolver
            DependencyResolver.SetResolver(New AutofacDependencyResolver(dependencyContainer))

        End Sub

        ''' <summary>
        ''' Registers the IOC types/services.
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Shared Function BuildIocContainer() As Autofac.IContainer

            Dim builder = New ContainerBuilder

            With builder
                ' Register Controllers
                .RegisterControllers(Assembly.GetExecutingAssembly())

                ' Custom MyCompany/Mvc objects
                .RegisterType(Of FormsAuthenticationService)().As(Of IFormsAuthenticationService)().InstancePerHttpRequest()
                .RegisterType(Of AccountMembershipService)().As(Of IMembershipService)().InstancePerHttpRequest()

                '***************************************************************
                '*  MyCompany service objects.
                '***************************************************************
                ' This is auto registration, it replaces all the individual registration lines of code below.
                builder.RegisterAssemblyTypes(GetType(CatalogCodeService).Assembly).
                    Where(Function(t) t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerHttpRequest()

                '.RegisterType(Of CatalogCodeService)().As(Of ICatalogCodeService)().InstancePerHttpRequest()
                '.RegisterType(Of ChargeCodeService)().As(Of IChargeCodeService)().InstancePerHttpRequest()
                '.RegisterType(Of CommentsService)().As(Of ICommentsService)().InstancePerHttpRequest()
                '.RegisterType(Of CommissionService)().As(Of ICommissionService)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigCriteriaService)().As(Of IConfigCriteriaService)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigGroupService)().As(Of IConfigGroupService)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigQuestionService)().As(Of IConfigQuestionService)().InstancePerHttpRequest()
                '.RegisterType(Of ContactService)().As(Of IContactService)().InstancePerHttpRequest()
                '.RegisterType(Of CustomerProductItemService)().As(Of ICustomerProductItemService)().InstancePerHttpRequest()
                '.RegisterType(Of CustomerService)().As(Of ICustomerService)().InstancePerHttpRequest()
                '.RegisterType(Of OrderItemService)().As(Of IOrderItemService)().InstancePerHttpRequest()
                '.RegisterType(Of OrderService)().As(Of IOrderService)().InstancePerHttpRequest()
                '.RegisterType(Of PriceBreakService)().As(Of IPriceBreakService)().InstancePerHttpRequest()
                '.RegisterType(Of PriceService)().As(Of IPriceService)().InstancePerHttpRequest()
                '.RegisterType(Of ProductItemService)().As(Of IProductItemService)().InstancePerHttpRequest()
                '.RegisterType(Of QuoteItemService)().As(Of IQuoteItemService)().InstancePerHttpRequest()
                '.RegisterType(Of QuoteService)().As(Of IQuoteService)().InstancePerHttpRequest()
                '.RegisterType(Of ShipmentItemService)().As(Of IShipmentItemService)().InstancePerHttpRequest()
                '.RegisterType(Of ShipmentService)().As(Of IShipmentService)().InstancePerHttpRequest()
                '.RegisterType(Of ShoppingCartItemService)().As(Of IShoppingCartItemService)().InstancePerHttpRequest()
                '.RegisterType(Of ShoppingCartService)().As(Of IShoppingCartService)().InstancePerHttpRequest()
                '.RegisterType(Of SystemTableItemService)().As(Of ISystemTableItemService)().InstancePerHttpRequest()

                '***************************************************************
                '*  MyCompany repository objects (used by service objects above)
                '***************************************************************
                ' This is auto registration, it replaces all the individual registration lines of code below.
                builder.RegisterAssemblyTypes(GetType(CatalogCodeRepository).Assembly).
                    Where(Function(t) t.Name.EndsWith("Repository")).AsImplementedInterfaces().InstancePerHttpRequest()

                '.RegisterType(Of CatalogCodeRepository)().As(Of ICatalogCodeRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ChargeCodeRepository)().As(Of IChargeCodeRepository)().InstancePerHttpRequest()
                '.RegisterType(Of CommentsRepository)().As(Of ICommentsRepository)().InstancePerHttpRequest()
                '.RegisterType(Of CommissionRepository)().As(Of ICommissionRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigCriteriaRepository)().As(Of IConfigCriteriaRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigGroupRepository)().As(Of IConfigGroupRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ConfigQuestionRepository)().As(Of IConfigQuestionRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ContactRepository)().As(Of IContactRepository)().InstancePerHttpRequest()
                '.RegisterType(Of CustomerProductItemRepository)().As(Of ICustomerProductItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of CustomerRepository)().As(Of ICustomerRepository)().InstancePerHttpRequest()
                '.RegisterType(Of IOrderItemRepository)().As(Of IOrderItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of OrderRepository)().As(Of IOrderRepository)().InstancePerHttpRequest()
                '.RegisterType(Of PriceBreakRepository)().As(Of IPriceBreakRepository)().InstancePerHttpRequest()
                '.RegisterType(Of PriceRepository)().As(Of IPriceRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ProductItemRepository)().As(Of IProductItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of QuoteItemRepository)().As(Of IQuoteItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of QuoteRepository)().As(Of IQuoteRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ShipmentItemRepository)().As(Of IShipmentItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ShipmentRepository)().As(Of IShipmentRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ShoppingCartItemRepository)().As(Of IShoppingCartItemRepository)().InstancePerHttpRequest()
                '.RegisterType(Of ShoppingCartRepository)().As(Of IShoppingCartRepository)().InstancePerHttpRequest()
                '.RegisterType(Of SystemTableItemRepository)().As(Of ISystemTableItemRepository)().InstancePerHttpRequest()
            End With

            Return builder.Build()

        End Function

    End Class

End Namespace

如您所见,Autofac 自动注册功能取代了使用 Unity.Mvc 所需的 40 多行代码(我将这些行留在里面并注释它们以突出显示)!!

享受!!

于 2012-06-06T12:55:32.003 回答
1

您是否考虑过使用命名约定? http://code.google.com/p/autofac/wiki/Scanning

var assemblyToScan = Assembly.GetExecutingAssembly();

builder.RegisterAssemblyTypes(assemblyToScan)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces();

builder.RegisterAssemblyTypes(assemblyToScan)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces();

您还可以使用这篇文章Autofac Scanning Assemblies for certain class type中介绍的基本类型进行注册

于 2012-06-06T20:13:13.813 回答