如何在控制器中访问IApplicationBuilder? [英] how to access IApplicationBuilder in a controller?

查看:96
本文介绍了如何在控制器中访问IApplicationBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道,是否有可能在startup.cs之外访问IApplicationBuilder属性?像在控制器中一样?

Just wondering, is that possible to access IApplicationBuilder propteries outside of the startup.cs? Like in a controller?

我知道它仅用于定义应用程序管道,那么解决方案是什么?诸如注册打包实例的服务,然后注入服务而不是IApplicationBuilder的东西?

I know it's only used to define the app pipeline so what would be the solution? Something like register a service that packages the instance, then inject the service instead of the IApplicationBuilder?

我正试图从Autofac找回我的DbConext.代码如下:

I'm trying to get back my DbConext from Autofac. Code is as following :

Business 项目中:

 public class AutofacBusinessModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule(new AutofacDataModule());
        }
    }

在数据项目中:

 public class AutofacDataModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<AppDbContext>().InstancePerLifetimeScope();
        }
    }

DbContext :

public class AppDbContext : DbContext
    {
        private const string DbContextName = "AppDbConnectionString";
        public DbSet<Contest> Contests { get; set; }

        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public AppDbContext()
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (optionsBuilder.IsConfigured) return;

            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
            var connectionString = configuration.GetConnectionString(DbContextName);
            optionsBuilder.UseSqlServer(connectionString,
                x => x.MigrationsAssembly("Cri.CodeGenerator.Data"));
        }

        public virtual void Commit()
        {
            base.SaveChanges();
        }
    }

以及Web项目中 startup.cs 中的 ConfigureServices :

And the ConfigureServices in startup.cs in Web project :

public IServiceProvider ConfigureServices(IServiceCollection services)
{


    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 = SameSiteMode.None;
    });

    var builder = new ContainerBuilder();

   builder.RegisterModule(new AutofacBusinessModule());


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

    services.AddScoped(sp => {
        var actionContext = sp.GetRequiredService<IActionContextAccessor>().ActionContext;
        var urlHelperFactory = sp.GetRequiredService<IUrlHelperFactory>();
        var urlHelper = urlHelperFactory.GetUrlHelper(actionContext);
        return urlHelper;
    });

    services.AddDistributedMemoryCache();
    builder.Populate(services);

    ApplicationContainer = builder.Build();

    //return the IServiceProvider implementation
    return new AutofacServiceProvider(ApplicationContainer);

}

我肯定会丢失一些东西,但是当涉及到DI和.net核心时真的是新手...

I'm surely missing something, but really newbie when it comes to DI and .net core...

-编辑-

在我的 Controller

  private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IApplicationBuilder _app;


        private const int NumberOfCharactersRepetion = 4;

        public UniqueCodesController(IHostingEnvironment hostingEnvironment, IApplicationBuilder app)
        {
            _hostingEnvironment = hostingEnvironment;
            _app = app;
        }

...

if (selectedAnswer == FileExtension.XLSX.GetStringValue())
                {
                    await FilesGenerationUtils.GenerateExcelFile(_app, uniqueCodesHashSet, model);
                }

GenerateExcelFile 方法中:

public static async Task GenerateExcelFile(IApplicationBuilder app, IEnumerable<string> hashSetCodes, ContestViewModel model)
        {
...

 try
                    {
                        var context = app.ApplicationServices.GetRequiredService<AppDbContext>();

                        var contest = new Contest
                        {
                            Name = model.ProjectName,
                            UserId = 1,
                            FileGenerationStatus = true,
                            FilePath = fileInfo.FullName
                        };
                        context.Contests.Add(contest);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

}

但是当我运行该应用程序时,我收到此消息:

But when I run the app, I get this message :

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Builder.IApplicationBuilder' while attempting to activate 'Cri.CodeGenerator.Web.Controllers.UniqueCodesController'.

推荐答案

听起来像您正在尝试获取 AppDbContext 的新实例.

Sounds like you're trying to get a new instance of AppDbContext.

如果必须将 GenerateExcelFile()保持为 static ,并想通过参数重用 AppDbContext ,则可以使其接受一个AppDbContext 的实例,而不是 IApplicationBuilder 的实例.

If you have to keep the GenerateExcelFile() as static and want to reuse AppDbContext via a parameter, you could make it accept an instance of AppDbContext instead of the IApplicationBuilder.

首先,只需直接注入这样的服务实例:

Firstly, simply inject such a service instance directly:

    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly AppDbContext _dbContext;

    // ...

    public UniqueCodesController(IHostingEnvironment hostingEnvironment, AppDbContext dbContext)
    {
        _hostingEnvironment = hostingEnvironment;
        _dbContext = dbContext;
    }

然后更改 GenerateExcelFile()以接受 AppDbContext


    public static async Task GenerateExcelFile(IApplicationBuilder app, IEnumerable<string>hashSetCodes, ContestViewModel model)
    public static async Task GenerateExcelFile(AppDbContext dbContext, IEnumerable hashSetCodes, ContestViewModel model)
    {
        ...

        try{
            var context = app.ApplicationServices.GetRequiredService();
            var contest = new Contest
            {
                Name = model.ProjectName,
                UserId = 1,
                FileGenerationStatus = true,
                FilePath = fileInfo.FullName
            };
            context.Contests.Add(contest);
            context.Contests.Add(contest);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

最后,您可以按以下方式调用它:

Finally, you could invoke it as below :

    await FilesGenerationUtils.GenerateExcelFile(_dbContext, uniqueCodesHashSet, model);


作为旁注,如果您无法在编译时确定所需的类型,并且想动态地解析某些服务类型,则您可以注入 IServiceProvider 而不是 IApplicationBuilder .这样,您可以根据需要解析任何实例:


As a side note, if you can't determine the required type at compile-time, and want to resolve some service type dynamically, you could inject an IServiceProvider instead of the IApplicationBuilder. In this way, You could resolve any instance as you like :

    var dbContext= sp.GetRequiredService<AppDbContext>();
    // or if you need a service only available within a scope 
    using(var scope = this._sp.CreateScope()){
        var _anotherDbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        ...
    }

以您的代码为例,您可以将 IServiceProvider 传递给 GenerateExcelFile(IServiceProvider sp,IEnumerable< string> hashSetCodes,ContestViewModel模型),并在 GenerateExcelFile()方法,您可以通过以下方式解析 AppDbContext :

Taking your code as an example, you could pass an IServiceProvider to GenerateExcelFile(IServiceProvider sp, IEnumerable<string> hashSetCodes, ContestViewModel model), and within the GenerateExcelFile() method, you could resolve the AppDbContext in the following way:

    public static async Task GenerateExcelFile(IServiceProvider sp, IEnumerable<string> hashSetCodes, ContestViewModel model)
    {
        ...

        var dbContext= sp.GetRequiredService<AppDbContext>();

        try{
            var contest = new Contest
            {
                Name = model.ProjectName,
                UserId = 1,
                FileGenerationStatus = true,
                FilePath = fileInfo.FullName
            };

            dbContext.Contests.Add(contest);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

这篇关于如何在控制器中访问IApplicationBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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