6

いくつかの依存関係を注入する必要がある ASP.NET MVC 3 アプリにアクション フィルターがあります。依存関係インジェクターとして Autofac.Mvc3 を使用しています。

autofac wikiによると、注入したい型を登録し、 を呼び出しRegisterFilterProvider、パブリック プロパティをアクション フィルターに配置するだけで、autofac はフィルターのインスタンス化中に適切なオブジェクトでプロパティを埋めます。

これが私のアクションフィルターの一部です:

Public Class LogActionAttribute
    Inherits ActionFilterAttribute

    Property tracer As TraceSource

    Public Overrides Sub OnActionExecuting(filterContext As System.Web.Mvc.ActionExecutingContext)
        ...
        tracer.TraceData(...)
        ...
    End Sub
End Class

ここに私のglobal.asaxの一部があります:

Public Class MvcApplication
    Inherits System.Web.HttpApplication

    Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)
        filters.Add(New MyHandleErrorAttribute)
        filters.Add(New LogActionAttribute)
    End Sub

    Sub Application_Start()
        InitSettingRepoEtc()
        ...
    End Sub

    Protected Shared Sub InitSettingRepoEtc()
        ...
        Dim builder = New ContainerBuilder
        builder.RegisterControllers(Reflection.Assembly.GetExecutingAssembly)
        ...
        builder.Register(Of TraceSource)(
            Function(x) New TraceSource("requests", SourceLevels.All)).InstancePerHttpRequest()
        ...
        builder.RegisterFilterProvider()
        Dim container = builder.Build
        DependencyResolver.SetResolver(New AutofacDependencyResolver(container))
        ...
    End Sub
End Class

直後にブレークポイントを配置SetResolverし、すぐに試したウィンドウで:

DependencyResolver.Current.GetService(Of TraceSource)

そしてautofacから無事にTraceSourceオブジェクトを取得できたので、登録はOKのようです。

しかし、OnActionExecuting私のtracer財産の間は空です。

私は何を取りこぼしたか?

4

1 に答える 1

4

プロバイダーの IIRC は、「グローバル」フィルターでは機能しません。

この機能を削除します。

Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)
    filters.Add(New MyHandleErrorAttribute)
    filters.Add(New LogActionAttribute)
End Sub

代わりに、グローバル フィルターを Autofac に直接登録します。

 builder.Register(Of MyHandleErrorAttribute)
     .As(Of IActionFilter)
     .PropertiesAutowired()
     .SingleInstance();

 builder.Register(Of LogActionAttribute)
     .As(Of IActionFilter)
     .PropertiesAutowired()
     .SingleInstance();

Autofac はフィルターを作成し、それらを適切に含めます。このアプローチの利点は、フィルターが属性から派生しないようにリファクタリングし、プロパティ インジェクションではなくコンストラクターを使用できることです。

于 2012-04-11T14:50:29.463 に答える