kim*_*udi 146 c# dependency-injection asp.net-core-mvc asp.net-core
我创建了一个.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; }
}
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
存储库(IBloggerRepository.cs和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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>();
}
Run Code Online (Sandbox Code Playgroud)
控制器(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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定我做错了什么.有任何想法吗?
Dav*_*idG 211
例外情况说它无法解析服务,WebApplication1.Data.BloggerRepository因为控制器上的构造函数要求使用具体类而不是接口.所以改变一下:
public BlogController(IBloggerRepository repository)
// ^
// Add this!
{
_repository = repository;
}
Run Code Online (Sandbox Code Playgroud)
hso*_*sop 26
我遇到了这个问题,因为在依赖项注入设置中,我缺少存储库的依赖项,而该存储库是控制器的依赖项:
services.AddScoped<IDependencyOne, DependencyOne>(); <-- I was missing this line!
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();
Run Code Online (Sandbox Code Playgroud)
riq*_*ang 23
在我的情况下,我试图为一个需要构造函数参数的对象进行依赖注入.在这种情况下,在启动期间,我只是从配置文件中提供了参数,例如:
var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));
Run Code Online (Sandbox Code Playgroud)
Pra*_* CS 13
Public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IEventRepository, EventRepository>();
}
Run Code Online (Sandbox Code Playgroud)
您忘记在启动ConfigureServices方法中添加“services.AddScoped” 。
Adr*_*ian 12
只有当有人和我一样的情况时,我才会使用现有数据库进行EntityFramework教程,但是当在模型文件夹上创建新的数据库上下文时,我们需要在启动时更新上下文,但不仅仅是在服务中.如果您有用户身份验证,则AddDbContext但AddIdentity也是如此
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<NewDBContext>()
.AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)
Sib*_*enu 10
我遇到了另一个问题,是的,已经为控制器的参数化构造函数添加了正确的接口。我所做的事情很简单。我只是去我的startup.cs文件,在那里我可以看到注册方法的调用。
public void ConfigureServices(IServiceCollection services)
{
services.Register();
}
Run Code Online (Sandbox Code Playgroud)
就我而言,此Register方法位于单独的类中Injector。因此,我不得不在其中添加新引入的接口。
public static class Injector
{
public static void Register(this IServiceCollection services)
{
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserDataService, UserDataService>();
}
}
Run Code Online (Sandbox Code Playgroud)
如果看到,此函数的参数为 this IServiceCollection
希望这可以帮助。
就我而言,Startup.cs 中的 .Net Core 3.0 API,在方法中
public void ConfigureServices(IServiceCollection services)
Run Code Online (Sandbox Code Playgroud)
我不得不添加
services.AddScoped<IStateService, StateService>();
Run Code Online (Sandbox Code Playgroud)
对于.NET 6.0
我只是在 Program.cs 上添加这一行
builder.Services.AddDbContext<DatabaseContext>();
Run Code Online (Sandbox Code Playgroud)
您需要DBcontext在启动时添加新服务
默认
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
Run Code Online (Sandbox Code Playgroud)
加上这个
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("NewConnection")));
Run Code Online (Sandbox Code Playgroud)
小智 6
对我来说,它可以按如下方式添加数据库上下文ConfigureServices:
services.AddDBContext<DBContextVariable>();
Run Code Online (Sandbox Code Playgroud)
由于一个很愚蠢的错误,我遇到了这个问题。我忘记了挂钩服务配置过程以在ASP.NET Core应用程序中自动发现控制器。
添加此方法可以解决该问题:
// Add framework services.
services.AddMvc()
.AddControllersAsServices(); // <---- Super important
Run Code Online (Sandbox Code Playgroud)
我必须在ConfigureServices中添加此行才能工作。
services.AddSingleton<IOrderService, OrderService>();
Run Code Online (Sandbox Code Playgroud)
我低于异常
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()
Run Code Online (Sandbox Code Playgroud)
因为我想注册工厂来创建 DbContext 派生类 IBlogContextFactory 的实例并使用 Create 方法来实例化博客上下文的实例,以便我可以使用下面的模式以及依赖注入,还可以使用模拟进行单元测试。
我想使用的模式是
public async Task<List<Blog>> GetBlogsAsync()
{
using (var context = new BloggingContext())
{
return await context.Blogs.ToListAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
但不是 new BloggingContext() 我想通过构造函数注入工厂,如下面的 BlogController 类
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的服务注册码
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>();
Run Code Online (Sandbox Code Playgroud)
以下是我的模型和工厂类
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; }
}
Run Code Online (Sandbox Code Playgroud)
----- 为了在 .net Core MVC 项目中修复这个问题——我对依赖项注册做了以下更改
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>(
sp => new BloggingContextFactory( () => sp.GetService<IBloggingContext>())
);
Run Code Online (Sandbox Code Playgroud)
简而言之,.net 核心开发人员负责注入工厂函数,在 Unity 和 .Net Framework 的情况下,它被处理了。
| 归档时间: |
|
| 查看次数: |
183857 次 |
| 最近记录: |