簡體   English   中英

在自定義授權屬性中,注入的對象始終為null

[英]Injected object is always null in custom authorize attribute

以下是我的MEF依賴關系解析器

public class MEFDependencyResolver : IDependencyResolver, System.Web.Http.Dependencies.IDependencyResolver
{
    private readonly CompositionContainer _container;

    public MEFDependencyResolver(CompositionContainer container)
    {
        if (container == null) throw new ArgumentNullException("container");

        _container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType == null) throw new ArgumentNullException("serviceType");

        var name = AttributedModelServices.GetContractName(serviceType);

        return Enumerable.Any(_container.Catalog.Parts.SelectMany(part => part.ExportDefinitions), e => e.ContractName == name) ? _container.GetExportedValue<object>(name) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        if (serviceType == null) throw new ArgumentNullException("serviceType");

        var name = AttributedModelServices.GetContractName(serviceType);

        return _container.GetExportedValues<object>(name);
    }

    public System.Web.Http.Dependencies.IDependencyScope BeginScope()
    {
        return this;
    }

    public void Dispose()
    {
    }

}

以下是我想補充的課程。

 [Export(typeof(IClientService))]
public class ClientService : IClientService { }

以下是我的自定義授權屬性。

public class CustomAuthorize : AuthorizeAttribute
{
    [Import]
    protected IClientService ClientService { get; set; }

    public string Status { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }

        return IsControllerAccessible(httpContext.User); 
    }

    private bool IsControllerAccessible(IPrincipal user)
    {
        var client = ClientService.GetClient();//ClientService object is null here.            

        return true;
    }
}

IClientService類型的對象ClientService始終為null。 在這種情況下,依賴解析器MEF似乎無法解析自定義屬性的依賴。

這里的實際問題是什么?

引導我。

我之前遇到了同樣的問題,最終使用了以下內容:

private IClientService _ClientService ;
    public IClientService ClientServiceObj
    {
        get
        {
            return _ClientService ??
                   (_ClientService = DependencyResolver.Current.GetService<IClientService>());
        }
        set { _ClientService = value; }
    }

然后使用ClientServiceObj來ClientService函數。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM