gpt4 book ai didi

c# - 解决多接口(interface)实现

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:15 24 4
gpt4 key购买 nike

在这种情况下,我的服务接口(interface)由两个服务类实现。

例如,

IFooServiceFooServiceFooWithExtraInfoService实现强>

这是界面:

public interface IFooService
{
Foo GetEntity(string fieldName, stringFieldValue);
}

这是 FooService:

public class FooService: BarService,  IFooService
{
public FooService(ILogService logservice): base(logservice)
{
}

public Foo GetEntity(string fieldName, string fieldValue)
{
//here goes the logic
}
}

这是FooWithExtraInfoService:

public class FooWithExtraInfoService: BarService, IFooService
{
public FooWithExtraInfoService(ILogService logservice): base(logservice)
{
}

public Foo GetEntity(string fieldName, string fieldValue)
{
//one possible option could be
var foo = new FooService(logservice).GetEntity(fieldName, fieldValue)
//do additional stuff
foo.SomeField = "abc";
}
}

如您所见,一个选项可能是创建 FooService 的新对象,然后告诉 unity 注册类型,其中 IFooServiceFooWithExtraInfoService 实现。

类似于:

container.RegisterType<IFooService, FooWithExtraInfoService>();

但是有没有其他方法可以让我不必创建 FooService 的新对象?

//one possible option could be
var fooService = new FooService(logservice).GetEntity(fieldName, fieldValue)
//do additional stuff

让 Unity 以某种方式处理它?<​​/p>

或者我应该为 FooWithExtraInfoService 创建不同的接口(interface)吗?

目前我不知道解决这个问题的最佳方法是什么。

任何建议都会有所帮助。

最佳答案

这似乎是 decorator pattern 的一个很好的候选者.

装饰器模式包装现有服务,为其添加额外的功能,而无需对其进行更改。这使您可以清楚地将 FooServiceFooWithExtraInfoService 的职责分开,并且仍然允许 DI 容器提供“内部”实例。

public class FooWithExtraInfoService : IFooService
{
private readonly IFooService fooService;

public FooWithExtraInfoService(IFooService fooService)
{
if (fooService == null)
throw new ArgumentNullException(nameof(fooService));
this.fooService = fooService;
}

public Foo GetEntity(string fieldName, string fieldValue)
{
// call the decorated instance of IFooService
var foo = this.fooService.GetEntity(fieldName, fieldValue);
//do additional stuff
foo.SomeField = "abc";
}
}

然后您只需要将它与您的 DI 容器连接起来,例如:

var instance = new FooWithExtraInfoService(new FooService(new LogService()));

在 Unity 中,可以这样注册:

container.RegisterType<ILogService, LogService>();

// Register FooService as a named service
container.RegisterType<IFooService, FooService>("foo");

// Register FooWithExtraInfoService and inject FooService into it
container.RegisterType<IFooService, FooWithExtraInfoService>(
new InjectionConstructor(new ResolvedParameter<IFooService>("foo")));

NOTE: An example of how you could make decorator registrations convention-based is in this answer.

与使用继承不同,装饰器与FooService松耦合ILogService 不需要传递到装饰器中,因此它可以转发到父类(super class)构造函数中。此外,只需更改 DI 配置,您就可以在 FooWithExtraInfoServiceFooService 之间轻松添加另一个装饰器类。

var instance = new FooWithExtraInfoService(
new FooDecorator1(
new FooService(new Logger())));

关于c# - 解决多接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49171999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com