将autofac与webapi和mvc5.1一起使用不适用于webapi

时间:2014-06-04 22:32:06

标签: autofac membershipreboot

我有一个同时使用mvc和webapi的项目。 这是一个会员重新启动应用程序,所以我采用了单个应用程序项目的示例,并稍微修改了它以适应。

DI适用于控制器,但是当我尝试调用webapi控制器时,我一直收到错误

  

确保控制器具有无参数的公共构造函数。

在使用带webapi的autofac时,我还需要做些什么吗?

这是我的startup.cs的代码

        public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "External", 
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive
        });
        ConfigureMembershipReboot(app);
    }

    private static void ConfigureMembershipReboot(IAppBuilder app)
    {
        System.Data.Entity.Database.SetInitializer(new System.Data.Entity.MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());
        //System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<DefaultMembershipRebootDatabase>());
        var cookieOptions = new CookieAuthenticationOptions
        {
            AuthenticationType = MembershipRebootOwinConstants.AuthenticationType
        };
        BuildAutofacContainer(app, cookieOptions.AuthenticationType);
        app.UseMembershipReboot(cookieOptions);
    }

    private static void BuildAutofacContainer(IAppBuilder app, string authType)
    {
        var builder = new ContainerBuilder();

        var config = CreateMembershipRebootConfiguration(app);

        builder.RegisterInstance(config).As<MembershipRebootConfiguration>();
        builder.RegisterType<DefaultUserAccountRepository>()
            .As<IUserAccountRepository>()
            .As<IUserAccountQuery>()
            .InstancePerLifetimeScope();
        builder.RegisterType<UserAccountService>().OnActivating(e =>
        {
            var owin = e.Context.Resolve<IOwinContext>();
            var debugging = false;
         #if DEBUG
            debugging = true;
         #endif
            e.Instance.ConfigureTwoFactorAuthenticationCookies(owin.Environment, debugging);
        })
        .AsSelf()
        .InstancePerLifetimeScope();
        builder.Register(ctx =>
        {
            var owin = ctx.Resolve<IOwinContext>();
            return new OwinAuthenticationService(authType, ctx.Resolve<UserAccountService>(), owin.Environment);
        })
        .As<AuthenticationService>()
        .InstancePerLifetimeScope();

        builder.Register(ctx=>HttpContext.Current.GetOwinContext()).As<IOwinContext>();
        builder.RegisterControllers(typeof(Startup).Assembly);

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

        var container = builder.Build();
        System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

1 个答案:

答案 0 :(得分:0)

这是1班轮:)

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);