1

我搜索了互联网和堆栈溢出,但根本无法弄清楚为什么我的 AutoFac 断然拒绝将任何东西注入任何控制器。我的代码如下 - 一切似乎都井井有条,但我收到以下消息:

尝试创建类型为“SimpleController”的控制器时发生错误。确保控制器有一个无参数的公共构造函数。

启动.cs

using System.Reflection;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataHandler.Serializer;
using Microsoft.Owin.Security.DataProtection;
using Owin;
using WebApiDependancyViaOwinTest.Models;

[assembly: OwinStartup(typeof(WebApiDependancyViaOwinTest.Startup))]

namespace WebApiDependancyViaOwinTest
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 
            builder.RegisterType<TestObject>().As<ITestObject>().InstancePerRequest();
            //ASP.NET Identity Related
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<TicketDataFormat>().As<ISecureDataFormat<AuthenticationTicket>>();
            builder.RegisterType<TicketSerializer>().As<IDataSerializer<AuthenticationTicket>>();
            builder.Register(c => new DpapiDataProtectionProvider().Create("Test")).As<IDataProtector>();
            var x = ApplicationDbContext.Create();
            builder.Register(c => x);
            builder.Register(c => new UserStore<ApplicationUser>(x)).AsImplementedInterfaces();
            builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager>
            {
                DataProtectionProvider = new DpapiDataProtectionProvider("Test")
            });

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            ConfigureAuth(app);
        }
    }

    public interface ITestObject
    {
        string Name { get; set; }
    }
    public class TestObject : ITestObject
    {
        public string Name { get; set; }
    }
}

启动.Auth.cs

using System;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using WebApiDependancyViaOwinTest.Providers;

namespace WebApiDependancyViaOwinTest
{
    public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

全球.asax.cs

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebApiDependancyViaOwinTest
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

简单控制器.cs

using System.Web.Http;

namespace WebApiDependancyViaOwinTest.Controllers
{
    public class SimpleController : ApiController
    {
        private readonly ITestObject _testObject;
        public SimpleController(ITestObject testObject)
        {
            _testObject = testObject;
        }

        [AllowAnonymous]
        [HttpGet]
        public string TestInjection()
        {
            return (_testObject == null).ToString();
        }
    }
}

AccountController.cs(片段)

[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    private const string LocalLoginProvider = "Local";
    private ApplicationUserManager _userManager;
    private readonly ITestObject _testObject;

    public AccountController(ApplicationUserManager userManager,
        ISecureDataFormat<AuthenticationTicket> accessTokenFormat,
        ITestObject testObject)
    {
        UserManager = userManager;
        AccessTokenFormat = accessTokenFormat;
        _testObject = testObject;
    }

    [AllowAnonymous]
    [HttpGet]
    public string TestInjection()
    {
        return (_testObject == null).ToString();
    }
4

0 回答 0