Created
March 28, 2019 10:01
-
-
Save seesharper/8f2130ee03c2e1c50521b769a485b68b to your computer and use it in GitHub Desktop.
LightInject TopShelf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class LightInjectServiceConfiguratorExtensions | |
{ | |
public static Func<T> GetFactory<T>() where T : class | |
{ | |
return () => ServiceFactoryExtensions.GetInstance<T>(LightInjectBuilderConfigurator.ServiceContainer); | |
} | |
public static ServiceConfigurator<T> ConstructUsingLightInject<T>(this ServiceConfigurator<T> configurator) where T : class | |
{ | |
Type[] interfaces = typeof(T).GetInterfaces(); | |
if (interfaces != null && interfaces.Length != 0 && typeof(ServiceControl).IsAssignableFrom(typeof(T))) | |
{ | |
configurator.WhenStarted((Func<T, HostControl, bool>)((T service, HostControl control) => service.Start(control))); | |
configurator.WhenStopped((Func<T, HostControl, bool>)((T service, HostControl control) => service.Stop(control))); | |
} | |
ServiceConfiguratorExtensions.ConstructUsing<T>(configurator, GetFactory<T>()); | |
return configurator; | |
} | |
public static ServiceConfigurator<T> ConstructUsingLightInject<T>(this ServiceConfigurator<T> configurator, Func<T, bool> start, Func<T, bool> stop) where T : class | |
{ | |
ServiceConfiguratorExtensions.ConstructUsing<T>(configurator, GetFactory<T>()); | |
configurator.WhenStarted((Func<T, HostControl, bool>)((T service, HostControl control) => start(service))); | |
configurator.WhenStopped((Func<T, HostControl, bool>)((T service, HostControl control) => stop(service))); | |
return configurator; | |
} | |
} | |
public class LightInjectBuilderConfigurator : HostBuilderConfigurator, Configurator | |
{ | |
public static IServiceContainer ServiceContainer | |
{ | |
get; | |
private set; | |
} | |
public LightInjectBuilderConfigurator(IServiceContainer serviceContainer) | |
{ | |
if (serviceContainer == null) | |
{ | |
throw new ArgumentNullException("serviceContainer"); | |
} | |
ServiceContainer = serviceContainer; | |
} | |
public IEnumerable<ValidateResult> Validate() | |
{ | |
yield break; | |
} | |
public HostBuilder Configure(HostBuilder builder) | |
{ | |
return builder; | |
} | |
} | |
public static class HostConfiguratorExtensions | |
{ | |
public static HostConfigurator UseLightInject(this HostConfigurator configurator, IServiceContainer serviceContainer) | |
{ | |
configurator.AddConfigurator(new LightInjectBuilderConfigurator(serviceContainer)); | |
return configurator; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment