【问题标题】:AspNet Core Scoped Dependency Interface SegregationAspNet Core 范围依赖接口隔离
【发布时间】:2018-09-11 14:49:30
【问题描述】:

所以,

// this doesn't work or make sense
services.AddScoped<IReadSomething>(sp => new Something());
services.AddScoped<IWriteSomething>(sp => new Something());

所以我有两个接口用于同一个类,IReadSomethingIWriteSomething,类只是 Something

它们需要限定范围,因为它们将数据子集从 HttpContext 传输到任意框架独立的“DTO”。

它们都应该引用Something 的同一个实例,显然一个只是公开了一些读取操作,而另一个公开了一些写入操作。所以它被写入中间件管道中的某个地方——应用程序的其余部分可以使用IReadSomething 并读取数据,这样我们就可以减少意外的数据覆盖。

在做,

services.AddScoped<IReadSomething, Something>();
services.AddScoped<IWriteSomething, Something>();

也没有任何意义,因为它应该为每个接口创建一个新实例。

让接口隔离和作用域依赖解析协同工作我缺少什么 - 我觉得我必须担心 ASP.NET Core 作用域服务工厂或其他什么?

我也在使用结构映射来解决我的主要依赖关系 - 所以使用它的答案很好。

【问题讨论】:

  • 我得到了结构图的答案,.Forward&lt;TFrom, TTo&gt;() AspNet Core 呢
  • @Nkosi 的 answer 为您介绍了 ASP.NET Core DI 容器 - 您可以轻松地接受他的回答并生成您自己的扩展方法来模拟 StructureMap 函数。

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


【解决方案1】:

将目标类设置为作用域,然后将其与所需的接口相关联

services.AddScoped<Something>();
services.AddScoped<IReadSomething>(sp => sp.GetService<Something>());
services.AddScoped<IWriteSomething>(sp => sp.GetService<Something>());

这样,对任一接口的调用都将返回作用域内的相同实例

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2018-06-07
    相关资源
    最近更新 更多