尚未注册类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务

2024-01-01

当我想开火时我遇到了问题add-migrationASP MVC Core 2 项目的命令。

尚未注册类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务。

这是我的启动.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; set; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContextPool<SampleArchContext>((serviceProvider, optionsBuilder) =>
        {
            optionsBuilder.UseInternalServiceProvider(serviceProvider); // It's added to access services from the dbcontext, remove it if you are using the normal `AddDbContext` and normal constructor dependency injection.
        });

        services.AddMvc(options =>
        {
            options.AllowEmptyInputInBodyModelBinding = true;
        }).AddJsonOptions(jsonOptions =>
        {
            jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });
    }

    public void Configure(
        ILoggerFactory loggerFactory,
        IApplicationBuilder app,
        IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            var builder = new ConfigurationBuilder()
             .SetBasePath(env.ContentRootPath)
             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
             .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
             .AddEnvironmentVariables();
            Configuration = builder.Build();

            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
        app.UseFileServer(new FileServerOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "bower_components")),
            RequestPath = "/bower_components",
            EnableDirectoryBrowsing = false
        });            
    }
}

程序.cs:

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.SetBasePath(env.ContentRootPath);
                config.AddInMemoryCollection(new[]
                       {
                         new KeyValuePair<string,string>("the-key", "the-value")
                       })
                       .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
                       .AddJsonFile($"appsettings.{env}.json", optional: true)
                       .AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddDebug();
                logging.AddConsole();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

context:

public interface IContext
{
    DbSet<Person> Persons { get; set; }
    DbSet<Country> Countries { get; set; }
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    int SaveChanges();
}
public class SampleArchContext : DbContext, IContext
{
    public SampleArchContext(DbContextOptions<SampleArchContext> options)
        : base(options)
    { }
    public DbSet<Person> Persons { get; set; }
    public DbSet<Country> Countries { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Country>(build =>
        {
            build.Property(category => category.Name).HasMaxLength(450).IsRequired();
        });
    }
    public override int SaveChanges()
    {
        var modifiedEntries = ChangeTracker.Entries()
            .Where(x => x.Entity is IAuditableEntity
                && (x.State == EntityState.Added || x.State == EntityState.Modified));

        foreach (var entry in modifiedEntries)
        {
            IAuditableEntity entity = entry.Entity as IAuditableEntity;
            if (entity != null)
            {
                string identityName = Thread.CurrentPrincipal.Identity.Name;
                DateTime now = DateTime.UtcNow;

                if (entry.State == EntityState.Added)
                {
                    entity.CreatedBy = identityName;
                    entity.CreatedDate = now;
                }
                else
                {
                    base.Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                    base.Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                }
                entity.UpdatedBy = identityName;
                entity.UpdatedDate = now;
            }
        }

        return base.SaveChanges();
    }
}
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<SampleArchContext>
{    
    public SampleArchContext CreateDbContext(string[] args)
    {
        var service = new ServiceCollection();
        service.AddOptions();
        //service.AddScoped<IHostingEnvironment, CustomHostingEnvironment>();
        service.AddSingleton<ILoggerFactory, LoggerFactory>();
        var serviceProvider = service.BuildServiceProvider();
        var hostingEnvirement = serviceProvider.GetRequiredService<IHostingEnvironment>();
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
           .SetBasePath(basePath: hostingEnvirement.ContentRootPath)
           //.SetBasePath(Directory.GetCurrentDirectory())
            .Build();
        service.AddSingleton(provider => configuration);
        serviceProvider = service.BuildServiceProvider();

        var builder = new DbContextOptionsBuilder<SampleArchContext>();
        var connectionString = configuration.GetConnectionString("AppDbContextConnection");
        builder.UseSqlServer(connectionString);
        return new SampleArchContext(builder.Options);
    }
}

这是我的appsetting.json :

应用程序设置.json:

{
  "ConnectionStrings": {
    "AppDbContextConnection": "Server=localhost; Database=CoreDbName;Trusted_Connection=True; MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

我查了很多资料都没有找到解决这个问题的方法,请问如何解决呢?


ASP.NET Core 2 中有一个新的应用程序模式。请参阅从 ASP.NET Core 1.x 迁移到 ASP.NET Core 2.0 https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/#update-main-method-in-programcs了解详情。

EF Core 不再尝试直接调用Startup.ConfigureServices()。在2.0版本中,它将寻找静态Program.BuildWebHost()方法并从中获取您的应用程序服务。

要采用新模式,请更新您的Program类看起来像这样。

public class Program
{
    public static IWebHost BuildWebHost(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
                config.SetBasePath(env.ContentRootPath);
                config.AddInMemoryCollection(new[]
                       {
                         new KeyValuePair<string,string>("the-key", "the-value")
                       })
                       .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false)
                       .AddJsonFile($"appsettings.{env}.json", optional: true)
                       .AddEnvironmentVariables();
            })
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddDebug();
                logging.AddConsole();
            })
            .UseIISIntegration()
            .UseDefaultServiceProvider((context, options) =>
            {
                options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
            })
            .UseStartup<Startup>()
            .Build();

        return host;
    }

    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尚未注册类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务 的相关文章

随机推荐

  • 如何在 Vim 上保存选项卡中的所有文件?

    如果我在 VIM 的选项卡中有多个文件 而我只编辑其中的几个文件 如何用一个命令保存它们 命令wa 短缺wall 将写入所有更改的缓冲区 您还可以使用 tabdo w 这绝对正是您想要的 并且概括得很好
  • .csproj 文件中自动生成的 IntermediateOutputPath

    从 Git 更新代码后 出现错误csproj 因为file路径不存在 这是引发错误的代码
  • 如何强制在抽象类的所有子类中定义构造函数

    我有一个定义抽象方法的抽象类 A 这意味着 要使类可实例化 必须实现所有抽象方法 我希望我的所有子类都实现一个以 2 个整数作为参数的构造函数 声明构造函数违背了我的目的 因为我希望在子类中定义构造函数 并且我对实现一无所知 此外 我不能将
  • MRC命令的附加协处理器寄存器的作用是什么?

    引用自 ARMMRC文档 MRC 2
  • UIView 中的黑色背景?

    我按照在线教程在子类 UIView 中进行绘制 本教程显示了一个具有白色背景的 UIView 我通过简单地更改超级的背景颜色来修复此问题 问题是 当触摸结束时 背景不会保持清晰 我不知道 我只是尝试将填充颜色设置为 uicolorclear
  • 链式哈希表与开放寻址哈希表

    有人可以解释这两种实现之间的主要区别 优点 缺点 吗 对于图书馆 建议采用什么实施方式 维基百科关于哈希表的文章 http en wikipedia org wiki Hash table对人们使用的不同哈希表方案提供了明显更好的解释和概述
  • 我可以将 Subversion 用于多 GB 数据集吗?

    该数据集包含 6766 个文件夹中的 97984 个文件 大小为 2 57 GB 其中很多是二进制文件 对我来说 这听起来并不那么重要 大约 50 个文件的每日数据更改率为数百 KB 但我担心颠覆会变得极其缓慢 无论如何 它从来都不是很快
  • 尝试在 Google App Engine 项目中创建备份时出现 404

    Setup 我按照以下步骤后遇到了404问题不被接受问题的答案App Engine 数据存储区 以编程方式备份 https stackoverflow com questions 15811982 appengine datastore b
  • 艰苦学习 Python 练习 48 帮助

    我正在学习 Python The Hard Way 并在练习 48 中遇到了挑战 您将获得大量代码作为单元测试 并要求我们创建一个函数以使单元测试通过 我不确定这段代码到底应该是什么样子 我已粘贴其中一个函数作为参考 它们看起来都与这个相似
  • 指定条形图中条形之间的空格

    我正在尝试用 R 生成一个条形图 条形的宽度不同 条形之间的间距也不同 例如我有一个矩阵 data lt matrix c 1 2 2 4 7 1 11 12 3 ncol 3 byrow T colnames data lt c Star
  • MongoDB (Java) - 如何运行保存在 javascript 文件中的查询?

    所以我有很多 js 文件 我之前用它们从命令行界面查询 MongoDB 但现在我希望能够通过 Java 运行这些相同的查询 我使用 Java 来支持依赖于查询中的信息 我如何使用来自 Java 驱动程序的 JavaScript 查询并返回一
  • Python下间歇性“sslv3警报握手失败”

    我有一个用 Java 编写的 REST API 在 JBoss 下运行 最近我们将 JVM 从 1 6 更新到了 1 7 这开始导致仅我们正在连接的 Python 客户端出现问题 Python 客户端间歇性地出现握手失败 我们编写了一个非常
  • 如何禁用 Maven Javadoc 插件中的 Javadoc 警告?

    我正在使用 Maven Javadoc 插件 它输出警告如下 ERROR home monperrus spoon src main java spoon visitor CtVisitor java 144 warning no para
  • python httplib2 证书验证失败

    我已经尝试了一切我能找到的方法来让它发挥作用 我正在为基于 python 的任务程序 称为 GTG 开发一个插件 我在 Opensuse Linux 上运行 Gnome 代码 Python 2 7 def initialize self I
  • 类型“文档”缺少类型中的以下属性

    所以我有一个 Node w Typescript REST API 我有一个注册方法 它创建一个用户并使用创建的用户的名字 姓氏 电子邮件进行响应 问题是我遇到此打字稿错误 显示 类型 文档 缺少类型 SavedUser 中的以下属性 名字
  • 使用 jaxb 解析包含 xi:includes 的 xml 时遇到问题

    我正在使用 JAXB 来解析 xml 我有一个如下的架构 以及在此架构上定义的两个 xml 文件 a xml 和 b xml a xml 通过 xi include xml 标签依赖于 b xml 请提交以下示例以获取更清晰的数据 I ha
  • 在 NSScrollView 中,垂直滑块始终指向视图的底部

    我正在开发 Mac 应用程序 在此应用程序中 我使用 NSScrollView 的实例作为滚动视图 我设置了一个 customView 它是此 ScrollView 中 NSView 的实例 如下所示 scrollView setDocum
  • Get-SPWeb 无法找到具有 ID 或 URL 的对象

    问题 我似乎无法弄清楚为什么会出现下面的错误 即使 SharePoint 网站以及被调用的文档库存在 文档库Lib1有文档 文件夹 文档库Lib2是空的 有人知道出了什么问题吗 ERROR Get SPWeb Cannot find an
  • 如何使用 VBScript 关闭特定文件夹?

    我正在尝试使用 VBScript 制作一个简单的程序 每次打开特定文件夹时都会关闭该文件夹 从而拒绝对该文件夹的访问 我已经成功地在许多文件夹中使用了此代码 但由于某种原因它不适用于C ProgramData Microsoft Windo
  • 尚未注册类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务

    当我想开火时我遇到了问题add migrationASP MVC Core 2 项目的命令 尚未注册类型 Microsoft AspNetCore Hosting IHostingEnvironment 的服务 这是我的启动 cs publ