ASP.NET Core Dependency Injection错误:尝试激活时无法解析类型服务

时间:2016-11-30 23:59:24

标签: c# dependency-injection asp.net-core asp.net-core-mvc

我创建了一个.NET Core MVC应用程序,并使用依赖注入和存储库模式将存储库注入我的控制器。但是,我收到了一个错误:

  

InvalidOperationException:尝试激活“WebApplication1.Controllers.BlogController”时无法解析类型“WebApplication1.Data.BloggerRepository”的服务。

模型(Blog.cs)

namespace WebApplication1.Models
{
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
}

DbContext(BloggingContext.cs)

using Microsoft.EntityFrameworkCore;
using WebApplication1.Models;

namespace WebApplication1.Data
{
    public class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
            : base(options)
        { }
        public DbSet<Blog> Blogs { get; set; }
    }
}

存储库(IBloggerRepository.cs&amp; BloggerRepository.cs)

using System;
using System.Collections.Generic;
using WebApplication1.Models;

namespace WebApplication1.Data
{
    internal interface IBloggerRepository : IDisposable
    {
        IEnumerable<Blog> GetBlogs();

        void InsertBlog(Blog blog);

        void Save();
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;

namespace WebApplication1.Data
{
    public class BloggerRepository : IBloggerRepository
    {
        private readonly BloggingContext _context;

        public BloggerRepository(BloggingContext context)
        {
            _context = context;
        }

        public IEnumerable<Blog> GetBlogs()
        {
            return _context.Blogs.ToList();
        }

        public void InsertBlog(Blog blog)
        {
            _context.Blogs.Add(blog);
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        private bool _disposed;

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            _disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

Startup.cs(相关代码)

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddScoped<IBloggerRepository, BloggerRepository>();

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

控制器(BlogController.cs)

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class BlogController : Controller
    {
        private readonly IBloggerRepository _repository;

        public BlogController(BloggerRepository repository)
        {
            _repository = repository;
        }

        public IActionResult Index()
        {
            return View(_repository.GetBlogs().ToList());
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _repository.InsertBlog(blog);
                _repository.Save();
                return RedirectToAction("Index");
            }
            return View(blog);
        }
    }
}

我不确定我做错了什么。有什么想法吗?

24 个答案:

答案 0 :(得分:157)

异常说它无法解析WebApplication1.Data.BloggerRepository的服务,因为控制器上的构造函数要求的是具体类而不是接口。所以改变一下:

public BlogController(IBloggerRepository repository)
//                    ^
//                    Add this!
{
    _repository = repository;
}

答案 1 :(得分:18)

在我的情况下,我试图为需要构造函数参数的对象进行依赖注入。在这种情况下,在启动期间,我只提供了配置文件中的参数,例如:

var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));

答案 2 :(得分:12)

只有当有人和我一样的情况时,我正在使用现有数据库进行EntityFramework教程,但是当在模型文件夹上创建新的数据库上下文时,我们需要在启动时更新上下文,但不仅仅是在services.AddDbContext中,如果您有用户身份验证,也可以使用AddIdentity

services.AddDbContext<NewDBContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<NewDBContext>()
                .AddDefaultTokenProviders();

答案 3 :(得分:9)

我遇到了这个问题,因为在依赖项注入设置中,我缺少存储库的依赖项,而该存储库是控制器的依赖项:

services.AddScoped<IDependencyOne, DependencyOne>();    <-- I was missing this line!
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();

答案 4 :(得分:5)

我有一个不同的问题,是的,我的控制器的参数化构造函数已经添加了正确的接口。我所做的是直截了当的。我只是转到我的startup.cs文件,在那里我可以看到注册方法的调用。

public void ConfigureServices(IServiceCollection services)
{
   services.Register();
}

就我而言,这个Register方法位于单独的类Injector中。所以我不得不在那里添加我新引入的接口。

public static class Injector
{
    public static void Register(this IServiceCollection services)
    {
        services.AddTransient<IUserService, UserService>();
        services.AddTransient<IUserDataService, UserDataService>();
    }
}

如果你看到,这个函数的参数是this IServiceCollection

希望这有帮助。

答案 5 :(得分:5)

就我而言,.Net Core 3.0 API Startup.cs, 在方法中

public void ConfigureServices(IServiceCollection services)

我必须添加

services.AddScoped<IStateService, StateService>();

答案 6 :(得分:2)

由于一个非常愚蠢的错误,我遇到了这个问题。我忘了挂勾服务配置过程以在ASP.NET Core应用程序中自动发现控制器。

添加此方法可以解决该问题:

// Add framework services.
            services.AddMvc()
                    .AddControllersAsServices();      // <---- Super important

答案 7 :(得分:2)

您需要在启动时为DBcontext添加新服务

默认

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

添加此

services.AddDbContext<NewDBContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("NewConnection")));

答案 8 :(得分:2)

你可能会错过这个:

services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();

答案 9 :(得分:2)

Public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IEventRepository, EventRepository>();           
}

您忘了在启动Configureservices方法上添加Addscope。

答案 10 :(得分:2)

甚至在到达类代码之前就已经完成了服务解析,因此我们需要检查依赖项注入。

就我而言,我添加了

        services.AddScoped<IMeasurementService, MeasurementService>();

在StartupExtensions.cs中

答案 11 :(得分:2)

我遇到了同样的问题,发现我的代码在初始化之前正在使用注入。

services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();

我知道这与问题无关,但是自从我被发送到此页面以来,我发现它对其他人很有用。

答案 12 :(得分:1)

哦,谢谢@kimbaudi,我遵循了这个习惯

https://dotnettutorials.net/lesson/generic-repository-pattern-csharp-mvc/

,并收到与您相同的错误。但是在阅读您的代码后,我发现我的解决方案是添加

  

services.AddScoped(IGenericRepository,GenericRepository);

进入StartUp.cs文件中的 ConfigureServices 方法=))

答案 13 :(得分:1)

对我来说,在 ConfigureServices 中添加数据库上下文是有效的,如下所示:

services.AddDBContext<DBContextVariable>();

答案 14 :(得分:1)

如果您正在使用AutoFac并收到此错误,则应添加“As”语句以指定具体实现所实现的服务。

IE中。你应该写:

containerBuilder.RegisterType<DataService>().As<DataService>();

而不是

containerBuilder.RegisterType<DataService>();

答案 15 :(得分:0)

我收到错误:“无法为所有.net核心版本解析依赖项xxxxxxxx”。我尝试了互联网上所有可用的东西,并且被困了好几天。我想出的唯一解决方案是在项目中添加nuget.config文件,然后使用dotnet restore使之工作。

nuget.config文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json" />
    <add key="AspNetCoreTools" value="https://dotnet.myget.org/F/aspnetcore-tools/api/v3/index.json" />
    <add key="NuGet" value="https://api.nuget.org/v3/index.json" />
  </packageSources>
</configuration>

答案 16 :(得分:0)

在项目的Startup.cs文件的ConfigureServices方法中

添加 services.AddSingleton();

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        // To register interface with its concrite type
        services.AddSingleton<IEmployee, EmployeesMockup>();
    }

有关更多详细信息,请访问以下URL:https://www.youtube.com/watch?v=aMjiiWtfj2M

对于所有方法(即AddSingleton与AddScoped与AddTransient),请访问以下网址:https://www.youtube.com/watch?v=v6Nr7Zman_Y&list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU&index=44

答案 17 :(得分:0)

我收到此错误是因为我声明了一个变量(在ConfigureServices方法上方),该变量是我的上下文。我有:

CupcakeContext _ctx

不确定我在想什么。我知道,如果您将参数传递给Configure方法,则这样做是合法的。

答案 18 :(得分:0)

此问题是因为您没有使用为其编写的接口来注册数据访问组件。尝试如下使用

services.AddTransient<IMyDataProvider, MyDataAccess>();`

答案 19 :(得分:0)

我替换了    services.Add(new ServiceDescriptor(typeof(IMyLogger), typeof(MyLogger))) 用    services.AddTransient<IMyLogger, MyLogger>()

对我有用。

答案 20 :(得分:0)

将BloggerRepository更改为IBloggerRepository

答案 21 :(得分:0)

通过使用如下所示的 CreateDefaultBuilder ,我尝试从Program.cs文件中进行插入时遇到了问题,但是最终通过跳过默认的资料夹来解决它。 (请参见下文)。

var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
    webBuilder.ConfigureServices(servicesCollection => { servicesCollection.AddSingleton<ITest>(x => new Test()); });
    webBuilder.UseStartup<Startup>();
}).Build();

似乎应该在ConfigureWebHostDefaults内部完成构建才能使其正常工作,因为否则将跳过配置,但是如果我错了,请纠正我。

这种方法效果很好:

var host = new WebHostBuilder()
.ConfigureServices(servicesCollection =>
{
    var serviceProvider = servicesCollection.BuildServiceProvider();
    IConfiguration configuration = (IConfiguration)serviceProvider.GetService(typeof(IConfiguration));
    servicesCollection.AddSingleton<ISendEmailHandler>(new SendEmailHandler(configuration));
})
.UseStartup<Startup>()
.Build();

这还显示了如何从

注入.net核心( IConfiguration )中已经预定义的依赖项

答案 22 :(得分:0)

我正处于例外之下

        System.InvalidOperationException: Unable to resolve service for type 'System.Func`1[IBlogContext]' 
        while attempting to activate 'BlogContextFactory'.\r\n at 
        Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)\r\n at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd[TKey, TValue, TArg] (ConcurrentDictionary`2 dictionary, TKey key, Func`3 valueFactory, TArg arg)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)\r\n at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)\r\n at lambda_method(Closure , IServiceProvider , Object[] )\r\n at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()

因为我想注册Factory来创建DbContext派生类IBlogContextFactory的实例,并使用Create方法实例化Blog Context的实例,以便我可以将以下模式与依赖关系注入一起使用,也可以将模拟用于单元测试。

我要使用的模式是

public async Task<List<Blog>> GetBlogsAsync()
        {
            using (var context = new BloggingContext())
            {
                return await context.Blogs.ToListAsync();
            }
        }

但是,我不想像下面的BlogController类那样通过构造函数注入工厂,而不是新的BloggingContext()

    [Route("blogs/api/v1")]

public class BlogController : ControllerBase
{
    IBloggingContextFactory _bloggingContextFactory;

    public BlogController(IBloggingContextFactory bloggingContextFactory)
    {
        _bloggingContextFactory = bloggingContextFactory;
    }

    [HttpGet("blog/{id}")]
    public async Task<Blog> Get(int id)
    {
        //validation goes here 
        Blog blog = null;
        // Instantiage context only if needed and dispose immediately
        using (IBloggingContext context = _bloggingContextFactory.CreateContext())
        {
            blog = await context.Blogs.FindAsync(id);
        }
        //Do further processing without need of context.
        return blog;
    }
}

这是我的服务注册代码

            services
            .AddDbContext<BloggingContext>()
            .AddTransient<IBloggingContext, BloggingContext>()
            .AddTransient<IBloggingContextFactory, BloggingContextFactory>();

以下是我的模型和工厂班级

    public interface IBloggingContext : IDisposable
{
    DbSet<Blog> Blogs { get; set; }
    DbSet<Post> Posts { get; set; }
}

public class BloggingContext : DbContext, IBloggingContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase("blogging.db");
        //optionsBuilder.UseSqlite("Data Source=blogging.db");
    }
}

public interface IBloggingContextFactory
{
    IBloggingContext CreateContext();
}

public class BloggingContextFactory : IBloggingContextFactory
{
    private Func<IBloggingContext> _contextCreator;
    public BloggingContextFactory(Func<IBloggingContext> contextCreator)// This is fine with .net and unity, this is treated as factory function, but creating problem in .netcore service provider
    {
        _contextCreator = contextCreator;
    }

    public IBloggingContext CreateContext()
    {
        return _contextCreator();
    }
}

public class Blog
{
    public Blog()
    {
        CreatedAt = DateTime.Now;
    }

    public Blog(int id, string url, string deletedBy) : this()
    {
        BlogId = id;
        Url = url;
        DeletedBy = deletedBy;
        if (!string.IsNullOrWhiteSpace(deletedBy))
        {
            DeletedAt = DateTime.Now;
        }
    }
    public int BlogId { get; set; }
    public string Url { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime? DeletedAt { get; set; }
    public string DeletedBy { get; set; }
    public ICollection<Post> Posts { get; set; }

    public override string ToString()
    {
        return $"id:{BlogId} , Url:{Url} , CreatedAt : {CreatedAt}, DeletedBy : {DeletedBy}, DeletedAt: {DeletedAt}";
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

-----要在.net Core MVC项目中解决此问题-我在依赖项注册上做了以下更改

            services
            .AddDbContext<BloggingContext>()
            .AddTransient<IBloggingContext, BloggingContext>()
            .AddTransient<IBloggingContextFactory, BloggingContextFactory>(
                    sp => new BloggingContextFactory( () => sp.GetService<IBloggingContext>())
                );

简而言之,.net核心开发人员负责注入工厂功能,在使用Unity和.Net Framework的情况下,该功能得到了照顾。

答案 23 :(得分:0)

我收到此错误消息,其中 ILogger注入到 .NET 5 类中。我需要添加类类型来修复它。

ILogger 记录器 --> ILogger 记录器