MVC3 & Unity.Mvc - PullRequest
       1

MVC3 & Unity.Mvc

0 голосов
/ 20 мая 2011

Странная проблема с моим проектом MVC3. Я следовал простому примеру МОК с использованием Unity.Mvc.

Хорошо работает, если мой объект и его интерфейс находятся в самом веб-проекте (в данном случае IMessageService и MessageService). Они явно работают, проблем нет.

Но когда я пытаюсь зарегистрировать свои объекты бизнес-сервисов из внешней сборки, они никогда не получают ничего (всегда ноль). Нет ошибок в App-Start при регистрации и т. Д.

У кого-нибудь есть идеи? Отчаянно здесь ....

UPDATE:

#Region "Imports"

Imports MyProject.Services
Imports MyProject.Services.Interfaces
Imports MyProject.Web.Mvc.Bootstrap
Imports MyProject.Web.Mvc.Services
Imports Microsoft.Practices.Unity
Imports Unity.Mvc3

#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(UnityDI), "Start")> 

#End Region

Namespace MyProject.Web.Mvc.Bootstrap

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

        ''' <summary>
        ''' Method to register the Unity 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 Start()

            ' Set DI resolver
            ' NOTE: ECD - The UnityDependencyResolver below is part of the Unity.Mvc3 assembly
            DependencyResolver.SetResolver(New UnityDependencyResolver(RegisterIocServices()))

        End Sub

        ''' <summary>
        ''' Registers the IOC types/services.   
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Shared Function RegisterIocServices() As IUnityContainer

            ' Create Unity dependency container
            Dim dependencyContainer As IUnityContainer = New UnityContainer

            ' Register the relevant types/services for the container here through classes or configuration
            With dependencyContainer
                .RegisterType(Of IFormsAuthenticationService, FormsAuthenticationService)()
                .RegisterType(Of IContactService, ContactService)()
                .RegisterType(Of IProductItemService, ProductItemService)()
                .RegisterType(Of ICustomerProductItemService, CustomerProductItemService)()
                .RegisterType(Of ISystemTableItemService, SystemTableItemService)()
                .RegisterType(Of ICatalogCodeService, CatalogCodeService)()
                .RegisterType(Of IOrderService, OrderService)()

                ' TEST: This one is in the MVC project and works, the above are an external library
                .RegisterType(Of IMessageService, MessageService)()
            End With

            Return dependencyContainer

        End Function

    End Class

End Namespace

Над кодом мой процесс регистрации. Я также попытался поместить это непосредственно в global.asax и у меня такое же поведение.

ОБНОВЛЕНИЕ 2

Разобрался с моей проблемой.

В моем контроллере у меня есть следующие свойства:

<Dependency()>
Private Property CatalogCodeService As ICatalogCodeService
<Dependency()>
Private Property ContactService As IContactService
<Dependency()>
Private Property CustomerProductItemService As ICustomerProductItemService

Но доступ к сервисам в методе действия всегда приводил к ошибке, что ни у одного из этих объектов не было экземпляров. Поэтому я предположил, что это был оригинальный код, который я разместил, или что-то там, как я регистрировался.

Оказывается, это был не мой регистрационный код, что совершенно нормально.

Вопрос?

Свойства должны быть "Public" !! Частный, Защищенный, Друг, все не работают на МОК. Как только я изменил эти свойства на «Public», все стало работать отлично.

Я не проверял, что это то же самое в C #, поэтому, если кто-то может добавить свои два цента, пожалуйста, обязательно сделайте это.

Пойди разберись ...

1 Ответ

1 голос
/ 05 апреля 2012

ОБНОВЛЕНИЕ II:

Вышеуказанная реализация использовала открытые свойства, которые следуют шаблону «Внедрение свойства» для внедрения зависимости.

С тех пор я переключился наболее подходящий метод «Внедрение в конструктор».

С этим изменением это свойство для моих сервисов, которое используют мои контроллеры, может быть закрытым и доступно только для чтения.

«Внедрение зависимостей в .NET»Марк Симанн, отличная книга.Я настоятельно рекомендую это всем, кто внедряет внедрение зависимостей, или тем, кто просто хочет больше узнать об этом.

...