【问题标题】:Web Api Core Project with Unity使用 Unity 的 Web Api 核心项目
【发布时间】:2018-02-06 10:51:52
【问题描述】:

我正在 .net 核心中创建 web api。我正在使用 Mac Sierra 10.12.3 和 Visual Studio for Mac 版本 7.3.3(build 12)。对于我在 Github 项目下面使用的参考。

https://github.com/unitycontainer/examples

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseUnityServiceProvider()   // Add Unity as default Service Provider
               .UseStartup<Startup>()
               .Build();
}

Startup.cs

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

    public IConfiguration Configuration { get; }


    public void ConfigureContainer(IUnityContainer container)
    {
        container.RegisterSingleton<IUserRepository, UserRepository>();

    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<ApplicationContext>(opts =>
               opts.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));


        // Add MVC as usual
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
    }
}

此链接代码适用于 Windows,但不适用于 Mac。

我正在尝试运行这个项目,它给了我以下错误

应用程序启动异常:System.ArgumentNullException: Value 不能为空。参数名称:source at System.Linq.Enumerable.Reverse[TSource](IEnumerable`1 源)在 Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() 已加载 '/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.0.5/System.Diagnostics.Debug.dll'。 跳过加载符号。模块经过优化和调试器选项 “只是我的代码”已启用。 [41m[1m[37mcrit[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost[6] Microsoft.AspNetCore.Hosting.Internal.WebHost:严重:应用程序 启动异常

System.ArgumentNullException:值不能为空。参数名称: System.Linq.Enumerable.Reverse[TSource](IEnumerable`1 来源)在 Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() 应用程序启动异常 System.ArgumentNullException:值不能为空。参数名称:source at System.Linq.Enumerable.Reverse[TSource](IEnumerable'1 源)在 Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() 抛出异常:'System.ArgumentNullException' in Microsoft.AspNetCore.Hosting.dll

编辑:

program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }

Start.cs

public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            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();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationContext>(opts =>
                    opts.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
            services.AddSingleton(typeof(IUserRepository<User, int>), typeof(UserRepository));
            services.AddMvc();
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }

在使用上层代码并且没有统一之后,它可以正常工作。

我们将不胜感激。

【问题讨论】:

  • 我找到了引发错误的确切行,并且看起来没有找到启动过滤器。 github.com/aspnet/Hosting/blob/dev/src/…
  • @Nkosi 我该如何解决。请帮帮我。
  • 我正在检查,但您也可以查看代码。至少现在你有了一个起点。
  • @Nkosi 我正在努力。
  • 仍在浏览代码,但这里有一个故障排除建议。删除UseUnityServiceProvider 并使用内置DI。检查项目是否将在没有它的情况下启动。如果确实如此,则确认统一容器是问题的原因,而不是其他问题。如果仍然失败,则问题不在于统一,而是与项目的配置方式有关。

标签: c# macos asp.net-core unity-container asp.net-core-webapi


【解决方案1】:

经过大量研究终于找到了解决方案

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .UseUnityServiceProvider()   // Add Unity as default Service Provider
            .UseStartup<Startup>()
            .Build();
    }

Startup.cs

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

        public IConfiguration Configuration { get; }

        // Configure Unity container
        public void ConfigureContainer(IUnityContainer container)
        {
            container.RegisterSingleton<IUserRepository, UserRepository>();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Container could be configured via services as well. 
            // Just be careful not to override registrations
            services.AddDbContext<ApplicationContext>(opts =>
                   opts.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
       
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                    builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyHeader()
                            .AllowAnyMethod();
                    });
            });

            // Add MVC as usual
            services.AddMvcCore().AddJsonFormatters();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }

在阅读了这篇博文后,我发现了差异。

https://offering.solutions/blog/articles/2017/02/07/difference-between-addmvc-addmvcore/

Don't forget to add the dependency injection for Unity Nuget Unity.Microsoft.DependencyInjection

感谢@Nkosi 的帮助和支持。

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2020-11-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2020-07-07
    • 2019-10-25
    相关资源
    最近更新 更多