在自定义授权属性中,注入的对象始终为空

时间:2017-05-01 00:41:10

标签: c# asp.net-mvc dependency-injection mef

以下是我的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无法解析自定义属性的依赖关系。

这里的实际问题是什么?

指导我。

1 个答案:

答案 0 :(得分:1)

我之前遇到过同样的问题,最后我使用了以下内容:

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

然后使用ClientServiceObj到ClientService函数。 希望这会有所帮助。