编程语言
首页 > 编程语言> > c#-在运行时注入值

c#-在运行时注入值

作者:互联网

我有一些存储库类,这些存储库类需要从Thread.CurrentPrincipal(即授权声明)中获取运行时值以及常规的单例类.

给定

public class MyRepository : IMyRepository
{
    private readonly DependencyClass _dependency;
    private readonly string claim;

    protected MyRepository(DependencyClass _dependency, string claim)
    {
        //...

在注册存储库时,如何注入声明?例如

unity.RegisterType<IMyRepository, MyRepository>(new HierarchicalLifetimeManager());
unity.RegisterType<DependencyClass>(new ContainerControlledLifetimeManager());

InjectionConstructor似乎与构造函数参数匹配,因此会导致运行时错误.仍然我更喜欢构造函数注入,但我不确定该怎么做.

解决方法:

I have repository classes that require runtime values

您的DI容器应建立包含注射剂/组分的对象图;包含应用程序逻辑的类.运行时数据不应注入组件的构造函数中,因为这会使构造,构建和验证对象图复杂化.

相反,应使用方法调用将运行时数据通过对象图传递.此类上下文运行时数据的一般解决方案是具有将此类上下文数据提供给其使用者的抽象.

例如,在您的情况下,IClaimsContext抽象可以解决问题:

public interface IClaimsContext {
    string CurrentClaim { get; }
}

使用这种抽象,创建一个从Thread.CurrentPrincipal读取声明的实现很简单,如下所示:

public sealed class ThreadClaimsContext : IClaimsContext {
    public string CurrentClaim {
        get { return Thread.CurrentPrincipal... /* get claims here */; }
    }
}

由于此实现不包含任何状态,因此可以毫无问题地将其注册为单例:

unity.RegisterInstance<IClaimsContext>(new ThreadClaimsContext());

现在,您的MyRepository可以仅依赖于IClaimsContext而不是字符串声明.

标签:asp-net-web-api,unity-container,c
来源: https://codeday.me/bug/20191028/1951410.html