Web API控制器上的统一解析实例 [英] unity resolve instance at web api controller

查看:97
本文介绍了Web API控制器上的统一解析实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在控制器级别解析类的实例?我想覆盖由unity创建的先前实例,并通过控制器分配此新值。

Is there any way to resolve the instance of a class at the controller level? I would like to override the previous instance created by unity and assign this new value via the controller.

问题是我不确定如何访问Web中的unity容器应用程序控制器。

Problem is I am not sure how to access the unity container in the web app controller.

这是我的代码:

存储库:

public class UserRepository: IUserRepository
{
    private UserInformation _userInfo; 
    public UserRepository(string headerValue)
    {       
        _userInfo = LoadUserData(headerValue);
    }

    public UserInformation GetUserInfo()
    {       
        return _userInfo;
    }
}

public class UserInformation
{
      public string FirstName;
      public string LastName;
}

统一配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        //Some code omitted
        config.DependencyResolver = new UnityDependencyResolver(UnityConfig.RegisterComponents());            
    }
}

public static class UnityConfig
{
    public static UnityContainer RegisterComponents()
    {
        //Unity Configuration
        var container = new UnityContainer();

        container.RegisterType<IUserRepository, UserRepository>(new InjectionConstructor("DummyHeaderValue"));          
        return container;
    }
}

控制器:

public class CustomerController : ApiController
{   
    public CustomerController()
    {
        //Something like this
        container.Resolve<UserRepository>(new InjectionConstructor(Request.GetHeader("RealHeaderValueFromHttpRequest")));
    }   
}

然后我应该可以使用更新后的<$整个应用程序中的c $ c> UserRepository 实例。

Then I should be able to use the updated UserRepository instance throughout the application.

是否有实现此想法的想法?

Any thoughts on how to achieve this?

编辑:正如@Nkosi指出的那样,我无权访问控制器构造函数中的Request。因此,让我再次改写我的问题:

As pointed out by @Nkosi I don't have access to Request in controller constructor. So let me rephrase my question again:

如何使用 UserInformation 对象初始化UserRepository,该对象包含有关当前详细信息用户?我要这样做的原因是,在我的整个应用程序中,我都需要用户详细信息,并且我不想通过每种方法传递用户ID。

How would I initialise UserRepository with UserInformation object which contains details about the current user? The reason I want to do this is that throughout my application I want user details and I don't want to pass User Id from each method

诸如此类:整个应用程序中的方法

Something like this: From any method throughout application

UserInformation obj = _userRepository().GetUserInfo();


推荐答案

创建抽象以获取对请求的访问权限

Create an abstraction to get access to the request

public interface IHeaderService {
    string RealHeaderValueFromHttpRequest();
}

其实现将可以访问上下文并请求获得所需的功能

Its Implementation will have access to the context and request to get the desired functionality

public class HeaderService : IHeaderService {
    public string RealHeaderValueFromHttpRequest() {
        return HttpContext.Current.Request.Headers["RealHeaderValueFromHttpRequest"];
    }
}

该服务现在将显式注入到从属存储库中

The service will now be explicitly injected into the dependent repository

public class UserRepository: IUserRepository {
    private readonly IHeaderService headerService;

    public UserRepository(IHeaderService headerService) { 
        this.headerService = headerService;
    }

    public UserInformation GetUserInfo() {
        var headerValue = headerService.RealHeaderValueFromHttpRequest();
        var _userInfo = LoadUserData(headerValue);
        return _userInfo;
    }

    //...
}

然后将存储库也显式注入到依赖的控制器中。

The repository will then also be explicitly injected into dependent controllers.

public class CustomerController : ApiController {
    private readonly IUserRepository repositoty;

    public CustomerController(IUserRepository repositoty) {
        this.repository = repository;        
    }

    public IHttpActionResult SomeAction() {
        //NOTE: Only access user info in a controller action
        var userInfo = repository.GetUserInfo();

        //... use user info.
    }

    //...
}

现在剩下的就是确保所有抽象及其实现都在依赖容器中注册了

Now all that is left is to make sure all abstractions and their implementations are registered with the dependency container

public static class UnityConfig {
    public static UnityContainer RegisterComponents() {
        //Unity Configuration
        var container = new UnityContainer();

        container.RegisterType<IUserRepository, UserRepository>();
        container.RegisterType<IHeaderService, HeaderService>();

        return container;
    }
}

这篇关于Web API控制器上的统一解析实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆