假设我有 3 个项目
- 常见
- 网络
- 核心
Web
和 Core
引用了 Common
。 Common
项目包含Web
和Core
的通用接口(interface)。
假设在这两个项目中我都有一些映射并且我想为此使用通用接口(interface)。例如,在 Web
项目上我想使用 AutoMapper,而在 Core
项目上我想使用其他东西。
对于 AutoMapper,我需要接口(interface)。
using AutoMapper;
namespace Common.Mapper
{
public interface IMapperConfiguration
{
IMapper GetMapper();
}
}
这在 Web
项目中工作,但我无法将此接口(interface)移动到 Common
项目,因为此接口(interface)依赖于 AutoMapper(IMapper 来自 AutoMapper)。
如何为此创建通用接口(interface)? 是否有一些我可以使用的设计模式?
Mapper 只是一个例子。我想知道如何解决这样的问题。 感谢您的帮助。
最佳答案
您需要使您的界面通用。如果您不使 AutoMapper 对两个项目通用,则它不能返回 IMapper 的实现。请原谅我,因为我不使用 automapper,但您会考虑将其包装在一个实现您自己的 IMapper 接口(interface)的类中,例如:
namespace Common.Mapper
{
public interface IMapper
{
void Map(...args...);
}
}
namespace Web.Mapper
{
public class Mapper : Common.Mapper.IMapper
{
public void Map(...args...)
{
AutoMapper.Map(...args...);
}
}
}
namespace Core.Mapper
{
public class Mapper : Common.Mapper.IMapper
{
public void Map(...args...)
{
SomeOtherMapper.Map(...args...);
}
}
}
关于c# - 不依赖特定逻辑的通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280896/