asp.net-core - System.TypeLoadException 无法加载类型 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions'

标签 asp.net-core asp.net-core-mvc

我收到这个错误:

Error when call "services.AddSession()" in ConfigureServices after migrate from RC2 to ASP.NET Core 1.0

enter image description here

详情如下:

Error Message: System.TypeLoadException Could not load type 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions' from assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'

项目.json:

    {
  "dependencies": {
    "ADMA.EWRS.Web.Security": "1.0.0-*",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    //=========================================================================
    //Murad Added
    //=========================================================================
    "Microsoft.AspNetCore.Authorization": "1.0.0",
    "Microsoft.AspNetCore.Authentication": "1.0.0",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Session": "1.0.0",
    "Autofac": "4.0.0-rc3-286",
    "Autofac.Extensions.DependencyInjection": "4.0.0-rc3-280",
    "Microsoft.AspNetCore.DataProtection": "1.0.0",
    "Microsoft.AspNetCore.Http.Abstractions": "1.0.0",
    "Microsoft.Extensions.Caching.Abstractions": "1.0.0",
    "Microsoft.Extensions.Logging.Abstractions": "1.0.0",
    "Microsoft.Extensions.Options": "1.0.0",
    "System.Security.Cryptography.Algorithms": "4.2.0",
    //=========================================================================
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "net461": {
      "dependencies": {
        "ADMA.EWRS.BizDomain": {
          "target": "project"
        },
        "ADMA.EWRS.Data.Models": {
          "target": "project"
        },
        "ADMA.EWRS.Security": {
          "target": "project"
        }
      }
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

启动.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using ADMA.EWRS.Web.Security.Claims;
using ADMA.EWRS.Web.Security;
using ADMA.EWRS.Security.Policy;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using ADMA.EWRS.Web.Security.Policy;
using ADMA.EWRS.Data.Models.Security;
using Autofac;
using Autofac.Extensions.DependencyInjection;

namespace ADMA.EWRS.Web.Core
{
    public partial 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();

            if (env.IsDevelopment())
            {
                // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
                //Murad : TODO : Add it later 
               //builder.AddApplicationInsightsSettings(developerMode: true);
            }
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        //Murad : When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            //Murad :: Add Security
            services.AddAuthorization(options =>
            {
                PoliciesManager.BuildSystemPolicies(options);
            });

            services.AddSession();

            // Murad Add this for RC2, remove it if release 1.0 after June :: AddRazorOptions
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .RequireRole(Groups.ADMAUserGroupName)
                                 .Build();
                config.Filters.Add(new AuthorizeFilter(policy));

                //Murad :: Info : https://damienbod.com/2015/09/15/asp-net-5-action-filters/
                config.Filters.Add(new Filters.AppFilter());


            });
            /*
             * Murad :: BUG Fixed 
            ).AddRazorOptions(options =>
            {
                var previous = options.CompilationCallback;
                options.CompilationCallback = context =>
                {
                    previous?.Invoke(context);
                    context.Compilation = context.Compilation.AddReferences(Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(typeof(ADMA.EWRS.Data.Models.Murad).Assembly.Location));
                };
            });
            */

            //var myAssemblies = AppDomain.CurrentDomain.GetAssemblies().Select(x => Microsoft.CodeAnalysis.MetadataReference.CreateFromFile(x.Location)).ToList();
            //services.Configure((Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions options) =>
            //{
            //    var previous = options.CompilationCallback;
            //    options.CompilationCallback = (context) =>
            //    {
            //        previous?.Invoke(context);

            //        context.Compilation = context.Compilation.AddReferences(myAssemblies);
            //    };
            //});


            //Murad : Replace ASP.NET Core DI with better AutoFac
            //services.AddScoped<IClaimsSecurityManager, ClaimsSecurityManager>();

            //Murad :: Add IoC i used AutoFac
            //Check : http://docs.autofac.org/en/latest/integration/aspnetcore.html

            // Add Autofac

            // Create the container builder.
            var containerBuilder = new Autofac.ContainerBuilder();
            containerBuilder.RegisterModule<IoC.DefaultModule>();

            //using Autofac.Extensions.DependencyInjection; it is extension method 
            containerBuilder.Populate(services);

            //build the container
            var container = containerBuilder.Build();

            // Return the IServiceProvider resolved from the container.
            return container.Resolve<IServiceProvider>();
        }

        // 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();

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

            app.UseStaticFiles();

            //Murad :: Replace in future with Cache Manager 
            app.UseSession(
                new SessionOptions()
                {
                    CookieName = Cookies.SessionsCookieName,
                    IdleTimeout = TimeSpan.FromMinutes(60)
                });

            //app.Map("/session", subApp =>
            //{
            //    subApp.Run(async context =>
            //    {
            //        int visits = 0;
            //        visits = context.Session.GetInt32("visits") ?? 0;
            //        context.Session.SetInt32("visits", ++visits);
            //        await context.Response.WriteAsync("Counting: You have visited our page this many times: " + visits);
            //    });
            //});

            //HttpContext.Session.SetString("Name", "Mike");

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = Cookies.AuthenticationCookieName,
                LoginPath = new PathString("/Account/Login/"),
                AccessDeniedPath = new PathString("/Account/Forbidden/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                SessionStore = new MemoryCacheTicketStore()
            });

            //Murad: Build Custom ADMA Claim Provider - If Allah give us more time in those FA people
            //app.UseClaimsTransformation(new ClaimsTransformationOptions
            //{
            //    Transformer = new ADMAClaimsTransformer()
            //});

            app.UseMvc(routes =>
            {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
}

最佳答案

是版本问题。检查 project.json 文件。我在下面给出了代码:

"Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
"Microsoft.AspNetCore.Diagnostics": "1.0.0",
"Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
"Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
"Microsoft.AspNetCore.Mvc": "1.0.1",

关于asp.net-core - System.TypeLoadException 无法加载类型 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210085/

相关文章:

asp.net-core - 重置 Entity Framework 7 迁移

c# - 如何使用 ASP.NET Core 进行流式处理

git - 使用基于 xproj 的 ASP.NET Core 项目时,Azure 构建停止工作

c# - asp.net core ControllerBase.User 没有实现 Controller

c# - ASP.NET Core 3.0 中获取当前经过身份验证的用户名的方法是什么?

c# - 使用 Angular 时无法使用默认路径加载 aspnet.core 服务器路由

c# - 当我的解决方案中有两个项目时,如何为 SignalR 3.0 指定正确的后端 URL?当前获取 404

angularjs - 如何在 MVC6 项目中安装 Angular2?

c# - .net-core中的Stackexchange.Redis超时异常

c# - ASP.NET Core 中的数据表类