Asp.net core asp.net核心和依赖注入示例poco类作为返回类型如何
查看此处文档中的DI部分Asp.net core asp.net核心和依赖注入示例poco类作为返回类型如何,asp.net-core,dependency-injection,Asp.net Core,Dependency Injection,查看此处文档中的DI部分 因此,使用下面的示例,如果在我的存储库中,我想返回某种POCO对象,该怎么办。这不也必须在configureservices中注册吗 using System.Collections.Generic; using DependencyInjectionSample.Models; namespace DependencyInjectionSample.Interfaces { public interface ICharacterRe
因此,使用下面的示例,如果在我的存储库中,我想返回某种POCO对象,该怎么办。这不也必须在configureservices中注册吗
using System.Collections.Generic;
using DependencyInjectionSample.Models;
namespace DependencyInjectionSample.Interfaces
{
public interface ICharacterRepository
{
IEnumerable<Character> ListAll();
void Add(Character character);
}
}
using System.Collections.Generic;
using System.Linq;
using DependencyInjectionSample.Interfaces;
namespace DependencyInjectionSample.Models
{
public class CharacterRepository : ICharacterRepository
{
private readonly ApplicationDbContext _dbContext;
public CharacterRepository(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public IEnumerable<Character> ListAll()
{
return _dbContext.Characters.AsEnumerable();
}
public void Add(Character character)
{
_dbContext.Characters.Add(character);
_dbContext.SaveChanges();
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase()
);
// Add framework services.
services.AddMvc();
// Register application services.
services.AddScoped<ICharacterRepository, CharacterRepository>();
services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();
}
使用System.Collections.Generic;
使用DependencyInjectionSample.Models;
命名空间依赖项InjectionSample.Interfaces
{
公共接口ICharacterRepository
{
IEnumerable ListAll();
无效添加(字符);
}
}
使用System.Collections.Generic;
使用System.Linq;
使用DependencyInjectionSample.Interfaces;
命名空间依赖性InjectionSample.Models
{
公共类CharacterRepository:ICharacterRepository
{
私有只读应用程序dbContext_dbContext;
公共字符库(ApplicationDbContext dbContext)
{
_dbContext=dbContext;
}
公共IEnumerable ListAll()
{
返回_dbContext.Characters.AsEnumerable();
}
公共空白添加(字符)
{
_dbContext.Characters.Add(字符);
_dbContext.SaveChanges();
}
}
}
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(选项=>
options.UseInMemoryDatabase()
);
//添加框架服务。
services.AddMvc();
//注册应用程序服务。
services.addScope();
services.AddTransient();
services.addScope();
services.AddSingleton();
AddSingleton(新操作(Guid.Empty));
services.AddTransient();
}
不,您不需要这样做。你对这种方法有意见吗?你说的是哪门课?没有问题,至少现在还没有。我正在构建一个新的类库,用于asp.net核心api项目。我正在以某种方式拆分我的类,以便使用存储库模式。我的每个respository类都有返回POCO对象而不是EF实体的方法。我想我的困惑在于存储库模式,而不是配置服务的DI设置。@Shyju-POCO类不被认为是一种依赖关系吗?它们只是传输数据的DTO。不要使POCOs复杂化。要了解更多关于DI的信息,您应该阅读免费提供的。该章有一节是关于“注入什么和不注入什么”。