Aplicação de Unity DI em Windows Services


Exemplo de consumo por serviço windows da aplicação DDD criada neste exercício.

I. Criar o projecto do tipo Windows Service e adicionar funcionalidades ao serviço. Descrição deste procedimento aqui.


II. Usar a gestão de pacotes NuGet através da UI da ferramenta no VS para instalar neste projecto o pacote mais recente do Unity pela Microsoft.


III. Juntar um timer ao windows service e determinar a cadência:
// Set up a timer to trigger every minute.  
System.Timers.Timer timer = new System.Timers.Timer();  
timer.Interval = 60000; // 60 seconds  
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);  
timer.Start();

e criar o respectivo timer event handler
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)  
{  
    // TODO: Insert activities here.  
}


VI. Adicionar o seguinte código à classe do serviço que herda do System.ServiceProcess.ServiceBase
using Unity;
using Unity.Lifetime;

Declarar o Unity Container
private static Lazy container;

Registar os tipos a usar
private static void RegisterTypes(UnityContainer container)
        {
            //Using Lifetime Managers: https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff647854(v%3dpandp.10)
container.RegisterType<IRepositoryAsync<Author>, AuthorRepository>(new PerRequestLifetimeManager());
container.RegisterType<IService<Author>, Service<Author>> (new PerRequestLifetimeManager());
container.RegisterType<IAuthorService, AuthorService>(new PerRequestLifetimeManager());
   }

Configurar o Unity Container
        ///         /// Configured Unity Container.
        ///         public static IUnityContainer Unitycontainer => container.Value;

public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)  
{  
               container =
                  new Lazy<iunitycontainer>(() =>
                  {
                      var container = new UnityContainer();
                      RegisterTypes(container);
                      return container;
                  });
   
            #region Unit of Work pattern with Unity DI
            var _dataContext = new PlutoContext();
            var _unitOfWork = new UnitOfWork(_dataContext);

            Unitycontainer.RegisterInstance<Idatacontext>(_dataContext, new ContainerControlledLifetimeManager());
            Unitycontainer.RegisterInstance<Idatacontextasync>(_dataContext, new ContainerControlledLifetimeManager());

            Unitycontainer.RegisterInstance<Iunitofwork>(_unitOfWork, new ContainerControlledLifetimeManager());
            Unitycontainer.RegisterInstance<Iunitofworkasync>(_unitOfWork, new ContainerControlledLifetimeManager());

            Unitycontainer.Resolve<Idatacontext>();
            Unitycontainer.Resolve<Idatacontextasync>();
            #endregion
   
   
     //Using Unity DI with a Console Application: https://stackoverflow.com/questions/29103508/using-unity-di-with-a-console-application
     //Dependency Injection with Unity: https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx#_Lifetime_Management
     ////https://www.tutorialspoint.com/design_pattern/command_pattern.htm
     Unitycontainer.Resolve<Program>().Run();
   
     _unitOfWork.Dispose();
   
     Unitycontainer.Dispose();
   
}


Referências: Using Unity DI with a Console ApplicationDependency Injection with UnityWalkthrough: Creating a Windows Service Application in the Component Designer

Licença CC BY-SA 4.0 Silvia Pinhão Lopes, 4.7.18
Print Friendly and PDF

Sem comentários:

Com tecnologia do Blogger.