我正在使用Autofac注入我工作良好的所有項目依賴關係。現在我添加了一個自定義授權屬性(我不需要像OWIN和Identity這樣非常複雜的功能)。自定義授權屬性依賴於數據層,因此我試圖將其注入屬性注入。然而,該屬性始終爲空。該代碼是下面:該噴射AuthorizationHelperAsp.Net Web Api和具有自定義授權屬性問題的Autofac(屬性注入)
public class CustomAuthorizationFilterAttribute : AuthorizeAttribute, IAutofacAuthorizationFilter
{
public IAuthorisationHelper AuthorisationHelper { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
**... removed for brevity**
**// TODO: this should be injected by autofac and is always null??**
if (AuthorisationHelper.IsValidUser(username, password, out roleOfUser))
{
var principal =
new GenericPrincipal((new GenericIdentity(username)),
(new[] { roleOfUser }));
Thread.CurrentPrincipal = principal;
return;
}
... removed for brevity
}
}
代碼:
public static IContainer Container()
{
var builder = new ContainerBuilder();
var assemblies = new List<Assembly>();
assemblies.Add(Assembly.Load("Kids.Math.Interfaces"));
assemblies.Add(Assembly.Load("Kids.Math.Data"));
assemblies.Add(Assembly.Load("Kids.Math.Business"));
assemblies.Add(Assembly.Load("Kids.Math.ImportExport"));
assemblies.Add(Assembly.Load("Kids.Math.Common"));
assemblies.Add(Assembly.Load("Kids.Math.Api"));
builder.RegisterAssemblyTypes(assemblies.ToArray()).
AsImplementedInterfaces();
builder.RegisterType(typeof(MathContext)).As(typeof (DbContext)).InstancePerRequest();
// Register web API controllers.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// TODO: this is not working, also this should be generic to register it for all controllers
// inject the authorisation filter
builder.RegisterType<AuthorisationHelper>().As<IAuthorisationHelper>();
builder.Register(c => new CustomAuthorizationFilterAttribute()).PropertiesAutowired()
.AsWebApiAuthorizationFilterFor<QuestionsImportController>()
.InstancePerRequest();
// Set the dependency resolver to be Autofac.
var container = builder.Build();
return container;
}
屬性被登記在一個FilterConfig作爲 filters.Add(新CustomAuthorizationFilterAttribute());
所有接線工作,但AuthorisationHelper始終爲空。
任何意見將不勝感激。
我這樣做。正如你可以看到上面的函數返回一個Container然後我使用它:var container = WebApiAutofacContainer.Container(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); ....沒有,沒有什麼會工作!正如我所提到的一切正在工作,除了財產注入! – user1829319
我編輯了我的答案。我不想假設你對容器做了什麼,所以我想確保你註冊的都是正確的:) – Ruskin
嗨拉斯金,謝謝你的回覆。我嘗試了你的建議,但仍然沒有運氣。物業將永遠是空的。 – user1829319