小编tom*_*dge的帖子

在.net核心中使用构造函数参数进行依赖注入

我看到了很多关于如何在.NET Core中使用DI的代码示例,但是没有一个使用构造函数参数.

例如:

  • 创建授权服务
  • 在构造函数中注入当前HTTP标头(X-Api-Key)
  • 在实施中检查我是否有权访问

在这里,我不仅需要在我的DI上使用DI,IAuthorizationService还需要在构造函数中注入令牌.我知道如何在Ninject中完成它,但是没有.NET Core DI的经验.

以下是我的例子.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddEntityFrameworkSqlite();
    services.AddDbContext<MainDbContext>();
    services.AddScoped<IAuthorizationService, AuthorizationService>(); // Inject current HttpContext header value as a constructor?
}
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection .net-core asp.net-core

11
推荐指数
1
解决办法
4722
查看次数

使用预加载的存储库通用方法 GetById

我正在使用实体框架,并希望在 Repository 类中创建通用的GetById方法并预先加载:

这是我使用延迟加载的方法:

public virtual TEntity GetById(object id)
  {
    return DbSet.Find(id);
  }
Run Code Online (Sandbox Code Playgroud)

我知道Find方法不支持急切加载,但是如何修改此方法以使用急切加载,因此我按如下方式使用此方法(例如):

_unitOfWork.MyRepository.GetById(includeProperties: "Users");
Run Code Online (Sandbox Code Playgroud)

c# entity-framework repository repository-pattern

2
推荐指数
1
解决办法
2622
查看次数