我开始使用依赖注入,但是很难处理一些第三方库类。例如,我的项目中有EPPlus库,其中有ExcelRange类,它没有实现接口。由于我正在使用该库,我发现我的代码明显依赖于它,并且无法正确地对某些代码部分进行单元测试。
因此,我的问题是如何有效地在第三方库类中使用依赖注入。
我开始使用依赖注入,但是很难处理一些第三方库类。例如,我的项目中有EPPlus库,其中有ExcelRange类,它没有实现接口。由于我正在使用该库,我发现我的代码明显依赖于它,并且无法正确地对某些代码部分进行单元测试。
因此,我的问题是如何有效地在第三方库类中使用依赖注入。
public interface IWrapperService
{
Method(Dto model);
Dto MethodProcess(Dto model);
}
public class WrapperService : IWrapperService
{
private readonly ThirdPartyLib _thirdPartyLib;
public WrapperService(ThirdPartyLib thirdPartyLib)
{
_thirdPartyLib = thirdPartyLib;
}
// Create your model - Dto
// Dto will help you in your logic process
//
public void Method(Dto model)
{
//extract some properties in you model that only needed in your third party library
_thirdPartyLib.Method(parameter needed);
}
public Dto MethodProcess(Dto model)
{
//extract some properties in you model that only needed in your third party library
ThirdPartyReturn value = _thirdPartyLib.MethodProcess(parameter needed);
// Do the mapping
var model = new Dto
{
property1 = value.property1 // Do the necessary convertion if needed.
.
.
}
return model;
}
.
.
.
}
public interface IOtherClass
{
...
}
public class OtherClass : IOtherClass
{
private readonly IWrapperService _wrapperService;
public void OtherClass(IWrapperService wrapperService)
{
_wrapperService= wrapperService;
}
.
.
}
对于依赖注入,您可以使用Microsoft Unity。它将为您的依赖项执行出色的工作。您可以像这样使用它:
var unity = new UnityContainer();
// This is how you will inject your ThirdPartyLib
// You can also do it this way - unity.RegisterType<ThirdPartyLib>() but of course we need to limit the usage of your ThirdPartyLib in
// our wrapper. We will not allowing directly access to Third Party Lib rather than wrapperService.
unity.RegisterType<IWrapperService, WrapperService>(new InjectionConstructor(new ThirdPartyLib()));
unity.RegisterType<IOtherClass, OtherClass>();
我同意 @Alexei Levenkov 的观点,你需要阅读一些Gang of Four (GOF)的相关内容来改进这个示例。把我的示例作为你的起点。
将第三方库包装起来可以带来以下优点:
少量缺点: