我已经搜索了互联网和堆栈溢出,但根本无法解决为什么我的AutoFac断然拒绝向任何控制器注入任何东西。我的代码如下 - 所有内容都有序,但我收到以下消息:
尝试创建类型的控制器时发生错误 'SimpleController'。确保控制器具有无参数 公共建设者。
Startup.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; }
}
}
StartUp.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);
}
}
}
的Global.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);
}
}
}
SimpleController.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();
}