Explorar o código

[ioc] added simple factory

Exilon %!s(int64=3) %!d(string=hai) anos
pai
achega
148d5688ed
Modificáronse 1 ficheiros con 52 adicións e 0 borrados
  1. 52 0
      Quick.IOC.pas

+ 52 - 0
Quick.IOC.pas

@@ -157,6 +157,28 @@ type
     procedure DoInvoke(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue);
   end;
 
+  IFactory<T> = interface
+  ['{92D7AB4F-4C0A-4069-A821-B057E193DE65}']
+    function New : T;
+  end;
+
+  TSimpleFactory<T : class, constructor> = class(TInterfacedObject,IFactory<T>)
+  private
+    fResolver : TIocResolver;
+  public
+    constructor Create(aResolver : TIocResolver);
+    function New : T;
+  end;
+
+  TSimpleFactory<TInterface : IInterface; TImplementation : class, constructor> = class(TInterfacedObject,IFactory<TInterface>)
+  private
+    fResolver : TIocResolver;
+  public
+    constructor Create(aResolver : TIocResolver);
+    function New : TInterface;
+  end;
+
+
   TIocContainer = class(TInterfacedObject,IIocContainer)
   private
     fRegistrator : TIocRegistrator;
@@ -187,6 +209,7 @@ type
     function AbstractFactory<T : class, constructor>(aClass : TClass) : T; overload;
     function AbstractFactory<T : class, constructor> : T; overload;
     function RegisterTypedFactory<TFactoryInterface : IInterface; TFactoryType : class, constructor>(const aName : string = '') : TIocRegistration<TTypedFactory<TFactoryType>>;
+    function RegisterSimpleFactory<TInterface : IInterface; TImplementation : class, constructor>(const aName : string = '') : TIocRegistration;
     procedure Build;
   end;
 
@@ -385,6 +408,11 @@ begin
   Result := Self.RegisterOptions<T>(options);
 end;
 
+function TIocContainer.RegisterSimpleFactory<TInterface, TImplementation>(const aName: string): TIocRegistration;
+begin
+  Result := fRegistrator.RegisterInstance<IFactory<TInterface>>(TSimpleFactory<TInterface,TImplementation>.Create(fResolver),aName).AsSingleton;
+end;
+
 function TIocContainer.Resolve(aServiceType: PTypeInfo; const aName: string): TValue;
 begin
   Result := fResolver.Resolve(aServiceType,aName);
@@ -744,4 +772,28 @@ begin
   if Result then aService := GlobalContainer.Resolve<T>;
 end;
 
+{ TSimpleFactory<T> }
+
+constructor TSimpleFactory<T>.Create(aResolver: TIocResolver);
+begin
+  fResolver := aResolver;
+end;
+
+function TSimpleFactory<T>.New: T;
+begin
+  Result := fResolver.CreateInstance(TClass(T)).AsType<T>;
+end;
+
+{ TSimpleFactory<TInterface, TImplementation> }
+
+constructor TSimpleFactory<TInterface, TImplementation>.Create(aResolver: TIocResolver);
+begin
+  fResolver := aResolver;
+end;
+
+function TSimpleFactory<TInterface, TImplementation>.New: TInterface;
+begin
+  Result := fResolver.CreateInstance(TClass(TImplementation)).AsType<TInterface>;
+end;
+
 end.