当您可以简单地使用以下模式时,为什么还要使用依赖注入框架?
unit uSomeServiceIntf;
interface
type
ISomeService = interface
procedure SomeMethod;
end;
var
CreateSomeService: function: ISomeService;
implementation
end.
unit uSomeServiceImpl;
interface
type
TSomeService = class(TInterfacedObject, ISomeService)
procedure DoSomething;
end;
function CreateSomeService: ISomeService;
implementation
function CreateSomeService: ISomeService;
begin
Result := TSomeService.Create;
end;
procedure TSomeService.DoSomeThing;
begin
...
end;
end.
unit uInitializeSystem;
interface
procedure Initialze;
implementation
uses
uSomeServiceIntf,
uSomeServiceImpl;
procedure Initialze;
begin
uSomeServiceIntf.CreateSomeService := uSomeServiceImpl.CreateSomeService;
end;
end.
我试图掌握使用框架而不是这样做的好处,但到目前为止,我只看到了这种简单方法的好处:
1)参数化构造函数更容易实现。例如: var CreateSomeOtherService: function(aValue: string);
2) 更快(无需在容器中查找)
3) 更简单
这就是我将如何使用它:
unit uBusiness;
interface
[...]
implementation
uses
uSomeServiceIntf;
[...]
procedure TMyBusinessClass.DoSomething;
var
someService: ISomeService;
begin
someService := CreateSomeService;
someService.SomeMethod;
end;
end.
您使用 DI 框架而不是这种方法的理由是什么?
使用 DI 框架会是什么样子?
据我所知,如果您使用 DI 框架,而不是针对接口注册具体类,然后系统的使用者会询问给定框架的实现。所以会有一个注册电话:
DIFramework.Register(ISomeInterface, TSomeInterface)
当您需要 ISomeInterface 实现时,您可以向 DI 框架询问它:
var
someInterface: ISomeInterface;
begin
someInteface := DIFrameWork.Get(ISomeInterface) as ISomeInterface;
现在很明显,如果您确实需要传递参数来创建 ISomeInterface,那么使用 DIFramework 会变得更加复杂(但使用上述方法很简单)。