如何从DI系统获取实例?

时间:2015-09-02 07:04:02

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

我正在尝试在vNext中重新创建HttpContext.Current,但我遇到了麻烦。

到目前为止的代码:

public class CurrentContext 
    {
        public IHttpContextAccessor ctx { get; private set; }

        public CurrentContext(IHttpContextAccessor accessor)
        {
            ctx = accessor;
        }
    }

services.AddTransient<CurrentContext>();

我想用:

public static class UserFactory
{
    public static void SetCurrentUser(User u)
    {
        //tryed to get the context but GetService returns null
        IHttpContextAccessor _context = ((CurrentContext)CallContextServiceLocator.Locator.ServiceProvider.GetService(serviceType: typeof(CurrentContext))).ctx;
        //add the user to the Session
    }
}

我现在如何在项目的任何地方获得CurrentContext的实例?

2 个答案:

答案 0 :(得分:0)

我不使用vNext DI系统,但我相信您应该为CurrentContext定义一个接口,例如

public class CurrentContextProvider : IContextProvider
{
    private readonly IHttpContextAccessor _context;

    public CurrentContextProvider(IHttpContextAccessor accessor)
    {
        _context = accessor;
    }

    public IHttpContextAccessor GetContext() {
        return _context;
    }
}

然后使用

services.AddScoped<IContextProvider, CurrentContextProvider>();

和电线

IHttpContextAccessor

但是如果你打算只使用上下文,为什么不直接依赖{{1}} - 你需要的地方?

答案 1 :(得分:0)

您应该在依赖类的构造函数中声明CurrentContext类型的变量:

public class SomeClassThatUsesCurrentContext
{
    private readonly SomeClassThatUsesCurrentContext currentContext;

    public SomeClassThatUsesCurrentContext(CurrentContext currentContext)
    {
        if (currentContext == null)
            throw new ArgumentNullException("currentContext");

        this.currentContext = currentContext;
    }
}

这些类可能出现在其他类的构造函数中。最后,您通常会从DI容器中解析高级类的单个实例。您执行此操作的位置称为composite root

而且,正如@janhartmann所说,通常你应该使用接口或抽象类而不是具体的类。

相关问题