c# - 使用 Unity 的 Web Api 核心项目

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

我正在 .net 核心中创建 web api。我正在使用 Mac Sierra 10.12.3 和 visual studio for Mac 版本 7.3.3(build 12)。作为引用,我在 Github 项目下面使用。

https://github.com/unitycontainer/examples

程序.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 中无效。

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

Application startup exception: System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.Reverse[TSource](IEnumerable`1 source) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() Loaded '/usr/local/share/dotnet/shared/Microsoft.NETCore.App/2.0.5/System.Diagnostics.Debug.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. [41m[1m[37mcrit[39m[22m[49m: Microsoft.AspNetCore.Hosting.Internal.WebHost[6] Microsoft.AspNetCore.Hosting.Internal.WebHost:Critical: Application startup exception

System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.Reverse[TSource](IEnumerable`1 source) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() Application startup exception System.ArgumentNullException: Value cannot be null. Parameter name: source at System.Linq.Enumerable.Reverse[TSource](IEnumerable'1 source) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() Exception thrown: '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();
    }

开始.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();
        }
    }

在使用上层代码并且没有 unity 之后它工作正常。

我们将不胜感激。

最佳答案

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

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 的帮助和支持。

关于c# - 使用 Unity 的 Web Api 核心项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48641224/

相关文章:

c# - 在 C# 中使用来自服务器资源管理器的数据连接

c# - 将对象列表保存到 XML 文件并使用 C# 加载该列表的最佳方法是什么?

c# - 使用 Task[] 对象引用时未设置为对象的实例

android - Titanium 找不到我的 Android Nexus 设备

linux - anaconda env 的 TensorFlow 问题

asp.net-core - 如何创建一个继承自标准 .Net Core 脚本标签助手的脚本标签助手

c# - 复杂模型+集合+IFormFile的REST API模型绑定(bind)

Windows、Mac 和 Linux (Unix) 上的 Java 程序

c# - 如何不为 .NET Core 控制台应用程序引用 Microsoft.NETCore.App 的依赖项?

c# - ZXing.Net 解码条形码给出错误 - 无法从 'System.Drawing.Bitmap' 转换为 'ZXing.LuminanceSource'