.NET Core - 更改控制器中的依赖项 [英] .NET Core - Changing dependency in Controller

查看:61
本文介绍了.NET Core - 更改控制器中的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Web 应用程序(.net core 2.2)并尝试替换控制器中对查询字符串参数的现有依赖.我知道,可以替换 Startup.cs 中的依赖项(ConfigureServices(IServiceCollection services) 方法).但问题是我无法访问控制器中的IServiceCollection".你们知道如何实现它吗?

这是在Startup中替换依赖的方法.ServiceCollectionDescriptorExtensions"具有替换"方法.

services.Replace(ServiceDescriptor.Scoped());

https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.extensions.servicecollectiondescriptorextensions?view=dotnet-plat-ext-3.1#Microsoft_Extensions_DependencyInjection_Extensions_ServiceCollectionDescriptorExtensions>

谢谢

解决方案

类似这样的...

公共类服务集合{

 public IConfiguration Configuration { get;}公共 IServiceCollection 服务 { 获取;}公共服务集合(){}public ServicesCollections(IConfiguration配置,IServiceCollection服务){配置=配置;服务 = 服务;}}///<总结>具有双重检查模式和实例参数 </summary> 的通用单例///<typeparam name="T"></typeparam>公共类 SingleObject其中 T : 类, new(){///<总结>锁定对象 </summary>私有静态只读对象_lockingObject = new object();///<总结>实例</summary>私有静态 T _singleObject;///<总结>ctor</summary>公共单对象(){}///<总结>带有参数 </summary> 的实例///<param name="param">参数</param>///<returns>实例</returns>公共静态 T 实例(参数动态 [] 参数){如果(_singleObject == null){锁(_lockingObject){如果(_singleObject == null){_singleObject = (T)Activator.CreateInstance(typeof(T), param);}}}返回_singleObject;}}

在您的初创企业 ---

public void ConfigureServices(IServiceCollection services){services.AddControllersWithViews();

 services.Configure(options =>{//此 lambda 确定给定请求是否需要用户同意非必要 cookie.options.CheckConsentNeeded = 上下文 =>真的;options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;});services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);服务.AddMvc().AddControllersAsServices();JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();services.AddRazorPages();var configs = Interfaces.SingleObject.Instance(Configuration, services);services.AddScoped();services.AddTransient(ctx => new SSO.Gateway.Web.Controllers.LoginController(configs));

ConfigureIdentityServer(services);

<代码> }

在您的控制器中 --

public class YourController : Controller{公共 YourController (ServicesCollections obj){配置 = obj.Configuration;服务 = obj.Services;配置服务();}公共 IConfiguration 配置 { 获取;}公共 IServiceCollection 服务 { 获取;}公共无效配置服务(){}

I am working on an web application (.net core 2.2) and trying to replace existing dependency over an querystring parameter in controller. I know, it is possible to replace dependency inside Startup.cs (ConfigureServices(IServiceCollection services) method). But problem is I cant access "IServiceCollection " in controller. Do you guys have an idea how to achive it?

This is the way to replace dependency in Startup. "ServiceCollectionDescriptorExtensions" has "Replace" method.

services.Replace(ServiceDescriptor.Scoped<IFooService,AnotherVersionOfFooService>());

https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.extensions.servicecollectiondescriptorextensions?view=dotnet-plat-ext-3.1#Microsoft_Extensions_DependencyInjection_Extensions_ServiceCollectionDescriptorExtensions

Thanks

解决方案

Something like this ...

public class ServicesCollections {

    public IConfiguration Configuration { get; }
    public IServiceCollection Services { get; }
    public ServicesCollections()
    {
    }
    public ServicesCollections(IConfiguration configuration, IServiceCollection services)
    {
        Configuration = configuration;
        Services = services;
    }


}


/// <summary> Generic singleton with double check pattern and with instance parameter </summary>
/// <typeparam name="T"></typeparam>
public class SingleObject<T> where T : class, new()
{
    /// <summary> Lock object </summary>
    private static readonly object _lockingObject = new object();

    /// <summary> Instance </summary>
    private static T _singleObject;

    /// <summary> ctor </summary>
    public SingleObject()
    {
    }

    /// <summary> Instance with parameter </summary>
    /// <param name="param">Parameters</param>
    /// <returns>Instance</returns>
    public static T Instance(params dynamic[] param)
    {
        if (_singleObject == null)
        {
            lock (_lockingObject)
            {
                if (_singleObject == null)
                {
                    _singleObject = (T)Activator.CreateInstance(typeof(T), param);
                }
            }
        }
        return _singleObject;
    }
}

In your start up ---

public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews();

        services.Configure<CookiePolicyOptions>(options =>
        {
            //This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
        }
       );

        services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);

        services.AddMvc()
            .AddControllersAsServices();

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        services.AddRazorPages();


       var configs = Interfaces.SingleObject<Interfaces.ServicesCollections>.Instance(Configuration, services);
        services.AddScoped<ServicesCollections>();
        services.AddTransient(ctx => new SSO.Gateway.Web.Controllers.LoginController(configs));

ConfigureIdentityServer(services);

    }

In your controller --

public class YourController : Controller
{
    public YourController (ServicesCollections obj)
    {
        Configuration = obj.Configuration;
        Services = obj.Services;
        ConfigureServices();
    }

    public IConfiguration Configuration { get; }

    public IServiceCollection Services { get; }

    public void ConfigureServices()
    { 

    }

这篇关于.NET Core - 更改控制器中的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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