使用Simple Injector检索声明

时间:2017-10-12 22:11:55

标签: c# asp.net-web-api dependency-injection ioc-container simple-injector

我正在处理的项目是将数据存储在我需要检索的索赔中。该项目使用Simple Injector作为其IoC容器,我已经实现了EnableHttpRequestMessageTracking,详见其文章:

Getting the current request’s HttpRequestMessage

但是,当尝试从声明中获取值作为请求的一部分时,它返回null。这在Simple Injector实现之前工作,方法是从控制器ActionContext.RequestContext中检索值,但这只能在控制器中使用,并且注入控制器的依赖项需要值。

更新(实际代码):

      private void ConfigureIoc(IAppBuilder app, HttpConfiguration config)
    {
        var container = new Container();
        container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle(); 
        container.Options.DefaultLifestyle = Lifestyle.Scoped;

        container.RegisterSingleton<IRequestMessageAccessor>(new RequestMessageAccessor(container));
        container.Register<IConnectionStringGenerator, ConnectionStringGenerator>();
        container.Register(() => container.GetInstance<DataAccess.IDataAccessConfigurationFactory>().GetConfiguration(container.GetInstance<IConnectionStringGenerator>().GetConnectionString()));
        container.Register<DataAccess.Repositories.Lookups.ILookupRepository, DataAccess.Repositories.Lookups.SQLLookupRepository>();

        container.EnableHttpRequestMessageTracking(config);
        container.RegisterWebApiControllers(config);

        container.Verify();

        //app.Use(async (context, next) => { using (AsyncScopedLifestyle.BeginScope(container)) { await next(); } });
        config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
    }

以下是其余部分:

public class ConnectionStringGenerator : IConnectionStringGenerator
{
    public IRequestMessageAccessor RequestMessage { get; set; }

    public ConnectionStringGenerator(IRequestMessageAccessor request)
    {
        RequestMessage = request;
    }

    public string GetConnectionString()
    {
        if (RequestMessage.CurrentMessage != null)
        {
            var requestContext = RequestMessage.CurrentMessage.GetRequestContext();
            if (requestContext != null)
            {
                System.Diagnostics.Debug.WriteLine(PrincipalInformationExtractor.GetInfo(requestContext.Principal, "dbServer"));

                var dbServer = PrincipalInformationExtractor.GetInfo(requestContext.Principal, "dbServer");
                var dbName = PrincipalInformationExtractor.GetInfo(requestContext.Principal, "dbName");
                if (!string.IsNullOrEmpty(dbServer) && !string.IsNullOrEmpty(dbName))
                {
                    return string.Format($"Server={dbServer};Database={dbName};Trusted_Connection=True");
                }
            }
        }
        return string.Empty;
    }
}

public interface IConnectionStringGenerator
{
    string GetConnectionString();
}

public sealed class RequestMessageAccessor : IRequestMessageAccessor
{
    private readonly Container container;

    public RequestMessageAccessor(Container container)
    {
        this.container = container;
    }

    public HttpRequestMessage CurrentMessage =>
        this.container.GetCurrentHttpRequestMessage();
}


public interface IRequestMessageAccessor
{
    HttpRequestMessage CurrentMessage { get; }
}

public static class PrincipalInformationExtractor
{
    public static string GetInfo(System.Security.Principal.IPrincipal objPrincipal, string dataKey)
    {
        var result = string.Empty;
        var principal = objPrincipal as ClaimsPrincipal;
        if (principal != null)
        {
            var value = principal.FindFirst(dataKey);
            if (value != null)
            {
                result = value.Value;
            }
        }

        return result;
    }
}

现在把这一行:

System.Diagnostics.Debug.WriteLine(
    PrincipalInformationExtractor.GetInfo(requestContext.Principal, "dbServer"));

在如下控制器中产生一个值:

System.Diagnostics.Debug.WriteLine(
    PrincipalInformationExtractor.GetInfo(ActionContext.RequestContext.Principal, "dbServer"));

有关如何获取这些值的任何输入?

0 个答案:

没有答案