9

私はしばらくの間、MVC 3 で autofac を使用しており、気に入っています。最近、プロジェクトを MVC 4 にアップグレードしましたが、Web Api ApiControllers を除いてすべてが機能しているようです。次の例外が発生しています。

An error occurred when trying to create a controller of type 'MyNamespace.Foo.CustomApiController'. Make sure that the controller has a parameterless public constructor.

これは、autofac を介した DI の問題のようです。私は何かを見逃していますか、それとも何かが進行中ですか?MVC4 はリリースされたばかりでベータ版なので、あまり期待していませんが、何か不足している可能性があると考えました。

4

2 に答える 2

10

MVC 4 および Web API のベータ バージョン用の NuGet で Autofac 統合パッケージをリリースしました。統合により、コントローラー要求ごとに Autofac ライフタイム スコープが作成されます (統合に応じて、MVC コントローラーまたは API コントローラー)。これは、コントローラーとその依存関係が各呼び出しの最後に自動的に破棄されることを意味します。両方のパッケージを同じプロジェクトに並べてインストールできます。

MVC4

https://nuget.org/packages/Autofac.Mvc4

http://alexmg.com/post/2012/03/09/Autofac-ASPNET-MVC-4-(ベータ)-Integration.aspx

Web API

https://nuget.org/packages/Autofac.WebApi/

http://alexmg.com/post/2012/03/09/Autofac-ASPNET-Web-API-(ベータ)-Integration.aspx

リンクが修正されました。

于 2012-03-09T05:55:00.223 に答える
4

これを自分のアプリの1つで構成しました。それを行うにはさまざまな方法がありますが、私はこのアプローチが好きです:

AutofacとASP.NETWebAPISystem.Web.Http.Services.IDependencyResolverの統合

System.Web.Http.Services.IDependencyResolverまず、インターフェイスを実装するクラスを作成しました。

internal class AutofacWebAPIDependencyResolver : System.Web.Http.Services.IDependencyResolver {

    private readonly IContainer _container;

    public AutofacWebAPIDependencyResolver(IContainer container) {

        _container = container;
    }

    public object GetService(Type serviceType) {

        return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType) {

        Type enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
        object instance = _container.Resolve(enumerableServiceType);
        return ((IEnumerable)instance).Cast<object>();
    }
}

そして、私は私の登録を保持する別のクラスを持っています:

internal class AutofacWebAPI {

    public static void Initialize() {
        var builder = new ContainerBuilder();
        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            new AutofacWebAPIDependencyResolver(RegisterServices(builder))
        );
    }

    private static IContainer RegisterServices(ContainerBuilder builder) {

        builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired();

        builder.RegisterType<WordRepository>().As<IWordRepository>();
        builder.RegisterType<MeaningRepository>().As<IMeaningRepository>();

        return
            builder.Build();
    }
}

次に、次の場所で初期化しますApplication_Start

protected void Application_Start() {

    //...

    AutofacWebAPI.Initialize();

    //...
}

これがお役に立てば幸いです。

于 2012-02-27T08:38:21.687 に答える