为什么你会使用依赖注入框架,当你可以简单地使用下面的模式?Delphi依赖注入:框架vs委托构造器
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)Simplier
这是我会怎么使用它:
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(但简单的上述方法)。
也许你可以添加一个使用DI容器的源代码示例来使声明和用法上的差异更清晰? – mjn 2011-05-10 06:27:45
不确定“便利”是什么意思?影响? – 2011-05-10 13:20:35
@Warren,也许OP想知道选择exeplified模式还是DI容器的原因...... – 2011-05-10 18:40:09