c# - 我的 ASP.NET Core MVVM Blazor 应用程序的依赖注入无法正常工作
问题描述
我在尝试应用依赖注入时遇到了麻烦。经过大量研究并查看 YouTube 上的各种视频和 Stack Overflow 上的答案后,我的 ITaskRepository 不断返回 null 而不是我的存储库的实例。查看我的代码,似乎我已经添加了所有正确的东西来使依赖注入工作。
我的基础存储库界面
using portfolio_backend.Data.Base;
using System.Collections.Generic;
namespace portfolio_backend.Business.Repositories.Base
{
public interface IBaseRepository<TEntity> where TEntity : BaseModel
{
void Add(TEntity model);
void Delete(TEntity model);
bool Exists(int Id);
TEntity Get(int Id);
IEnumerable<TEntity> GetAll();
void Update(int Id, TEntity model);
}
}
我的 BaseRepository 类
using Microsoft.EntityFrameworkCore.Internal;
using portfolio_backend.Data;
using portfolio_backend.Data.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace portfolio_backend.Business.Repositories.Base
{
public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : BaseModel
{
protected PortfolioContext _context;
public BaseRepository(PortfolioContext context)
{
_context = context;
}
public void Add(TEntity model)
{
if (!Exists(model.Id))
{
_context.Set<TEntity>().Add(model);
_context.SaveChanges();
}
}
public void Delete(TEntity model)
{
if (Exists(model.Id))
{
_context.Set<TEntity>().Remove(model);
_context.SaveChanges();
}
}
public bool Exists(int Id)
{
return _context.Set<TEntity>().Any(model => model.Id == Id);
}
public TEntity Get(int Id)
{
return _context.Set<TEntity>().FirstOrDefault(model => model.Id == Id);
}
public IEnumerable<TEntity> GetAll()
{
return _context.Set<TEntity>().ToList();
}
public void Update(int Id, TEntity model)
{
var modelToFind = Get(Id);
_context.Set<TEntity>().Update(modelToFind);
_context.SaveChanges();
}
}
}
我的 ITaskRepository 接口
using portfolio_backend.Business.Repositories.Base;
using portfolio_backend.Data;
using System.Collections.Generic;
namespace portfolio_backend.Business.Repositories
{
public interface ITaskRepository : IBaseRepository<Task>
{
IEnumerable<Task> GetTaskByProjects(int ProjectId);
}
}
任务存储库实现
using portfolio_backend.Business.Repositories.Base;
using portfolio_backend.Data;
using System.Collections.Generic;
using System.Linq;
namespace portfolio_backend.Business.Repositories
{
public class TaskRepository : BaseRepository<Task>, ITaskRepository
{
public TaskRepository(PortfolioContext context) : base(context)
{
}
public IEnumerable<Task> GetTaskByProjects(int ProjectId)
{
return _context.Tasks.OrderByDescending(task => task.Project.Id == ProjectId).ToList();
}
}
}
我的创业班:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using portfolio_backend.Business.Repositories.Base;
using portfolio_backend.Business.Repositories;
using portfolio_backend.Data;
using Blazorise;
using Blazorise.Bootstrap;
using Blazorise.Icons.FontAwesome;
namespace portfolio_backend.Presentation
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<PortfolioContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("portfolio")));
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
services.AddScoped<ITaskRepository, TaskRepository>();
services.AddBlazorise(options =>{
options.ChangeTextOnKeyPress = true;})
.AddBootstrapProviders()
.AddFontAwesomeIcons();
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.ApplicationServices
.UseBootstrapProviders()
.UseFontAwesomeIcons();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
我正在尝试对以下两个类应用依赖注入:
Tasks.razor.cs(Blazor 组件的代码隐藏)
using portfolio_backend.Business;
using portfolio_backend.Business.Repositories;
namespace portfolio_backend.Presentation.Pages
{
public partial class Tasks
{
private ITaskRepository _taskRepository;
private TaskViewModel _taskViewModel => new TaskViewModel(_taskRepository);
protected override void OnInitialized()
{
_taskViewModel.SeedTasks();
}
}
}
以及该组件的视图模型
using portfolio_backend.Business.Repositories;
using portfolio_backend.Data;
using System.Collections.Generic;
namespace portfolio_backend.Business
{
public class TaskViewModel
{
private ITaskRepository _taskRepository {get; set;}
private List<Task> _allTasks;
public TaskViewModel(ITaskRepository repository)
{
_taskRepository = repository;
}
public List<Task> AllTasks
{
get => _allTasks;
set => _taskRepository.GetAll();
}
public void SeedTasks()
{
_taskRepository.Add( new Task { Description = "Task 1"} );
_taskRepository.Add(new Task { Description = "Task 2" });
_taskRepository.Add(new Task { Description = "Task 3" });
}
}
}
_taskRepository 总是返回 null,这是出现的错误消息:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
我能做些什么来解决这个问题?或者在这种情况下如何更好地应用 DI?
更新:
我根据评论中建议的解决方案之一进行了以下更改:
using portfolio_backend.Business;
using portfolio_backend.Business.Repositories;
namespace portfolio_backend.Presentation.Pages
{
public partial class Tasks
{
private ITaskRepository _taskRepository;
private TaskViewModel _taskViewModel;
public Tasks(ITaskRepository repository)
{
_taskRepository = repository;
_taskViewModel = new TaskViewModel(_taskRepository);
}
protected override void OnInitialized()
{
_taskViewModel.SeedTasks();
}
}
}
这将触发以下错误:
MissingMethodException: No parameterless constructor defined for type 'portfolio_backend.Presentation.Pages.Tasks'.
正如错误提示的那样,我添加了一个额外的无参数构造函数
using portfolio_backend.Business;
using portfolio_backend.Business.Repositories;
namespace portfolio_backend.Presentation.Pages
{
public partial class Tasks
{
private ITaskRepository _taskRepository;
private TaskViewModel _taskViewModel;
public Tasks()
{
}
public Tasks(ITaskRepository repository)
{
_taskRepository = repository;
_taskViewModel = new TaskViewModel(_taskRepository);
}
protected override void OnInitialized()
{
_taskViewModel.SeedTasks();
}
}
}
上面的更改在 taskRepository 为空时产生了相同的问题。
解决方案
在您对最初的问题进行编辑之后,您似乎正在对未注册的类使用依赖注入机制:Tasks。这个类是如何实现的?
如果您想在特定类上使用 DI,您应该像使用 ITaskRepository 一样注册它。
将以下行添加到您的 ConfigureServices() 方法:
services.AddScoped<Tasks>();
推荐阅读
- c++ - 使用函数为构造函数提供 int 参数时值的意外反转
- ios - 在任何 iOS 设备上复制 CVPixelBuffer
- excel - 如何将lastcolumn(而不是lastrow)应用到一个范围内?
- reactjs - 使用 NextJS 链接,如何传递对象客户端?
- c# - 从异步方法调用异步方法关闭应用程序
- c# - Xtratab 控件根据 C# winforms 中的菜单选项更改标签页
- gradle - AndroidStudio 3.4:“Gradle 项目同步失败”Build.Gradle(应用程序)中的解析错误
- minecraft - 在 bukit 1.13 中双倍到字符串并返回错误
- javascript - 如何使用Vue根据选中的复选框在输入中修改字符串?
- html - ui 水平居中到左侧的锚点而不是中心