I am developing a Windows service to perform periodic operations, can I use Unity to input my classes from another library?
I want to use the [Dependency] attribute for my services, registering components at the Windows service entry point.
Example:
static class Program { static void Main() { ServiceBase[] ServicesToRun; UnityConfig.RegisterComponents(); ServicesToRun = new ServiceBase[] { new EventChecker() }; ServiceBase.Run(ServicesToRun); } } public static class UnityConfig { public static void RegisterComponents() { UnityContainer container = new UnityContainer(); container.RegisterType<IEventBL, EventBL>(); } } public partial class EventChecker : ServiceBase { private Logger LOG = LogManager.GetCurrentClassLogger(); [Dependency] public Lazy<IEventBL> EventBL { get; set; } protected override void OnStart(string[] args) { var events = EventBL.Value.PendingExecution(1); } }
In this case, EventBL is always null, so [Dependency] on one is not allowed. There is no way to make it work?
Thanks!
Solution found:
After writing the answer, I found a possible solution that calls the container creation method for creating the service class:
UnityContainer container = new UnityContainer(); UnityConfig.RegisterComponents(container); ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { container.BuildUp(new EventChecker()) }; ServiceBase.Run(ServicesToRun);
If you know any other solution, share it :)
c # dependency-injection unity-container windows-services
juan25d
source share