使用Unity将存储库注入ServiceAuthorizationManager

时间:2012-06-25 15:43:31

标签: wcf unity-container wcf-rest api-key

我想将一个存储库(使用unity)注入ServiceAuthorizationManager实现。有可能吗?

 public class APIKeyAuthorization : ServiceAuthorizationManager
    {


        private readonly IKeysService _keysService;

        public APIKeyAuthorization(KeysService keysService)
        {
            _keysService = keysService;
        }

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            //var _keysService = new KeysService();


            string key = GetAPIKey(operationContext);

            string endpoint = GetEndpoint(operationContext); //ip address

            if (_keysService.IsValidKey(key, endpoint))
            {
                return true;
            }
            else
            {
                // Send back an HTML reply
                CreateErrorReply(operationContext, key);
                return false;
            }
        }

1 个答案:

答案 0 :(得分:1)

您无需向容器注册APIKeyAuthorization。 Unity可以自行解决具体的类。 如果您想将APIKeyAuthorization作为ServiceAuthorizationManager的另一个实现注入,则必须使用容器注册该映射

container.RegisterType<ServiceAuthorizationManager, APIKeyAuthorization>();

Unity会将IKeyService的注册实现(在您的情况下是KeyService的实例)注入APIAuthorization的构造函数。

尝试

APIAuthorization auth = container.Resolve<APIAuthorization>();

你会看到Unity为你解析IKeyService

但请不要误以为abuse Unity as a ServiceLocator

而是将容器连接到composition root of your application中,并仅从容器中解析顶级对象。