public override void Prepare() { var registrar = new ContainerRegistrar(); registrar.RegisterType<ISingleton, Singleton>(Lifetime.Singleton); registrar.RegisterType<ITransient, Transient>(Lifetime.Transient); registrar.RegisterType<ICombined, Combined>(Lifetime.Transient); this.container = registrar.Build(); registrar = new ContainerRegistrar(); registrar.RegisterType<ICalculator, Calculator>(Lifetime.Transient); var containerWithLoggingInterception = registrar.Build(); containerWithLoggingInterception.AddDecorator(new GriffinLoggingDecorator()); this.containerWithLoggingInterception = containerWithLoggingInterception; }
public override void Prepare() { var registrar = new ContainerRegistrar(); RegisterBasic(registrar); RegisterPropertyInjection(registrar); this.container = registrar.Build(); registrar = new ContainerRegistrar(); registrar.RegisterType<ICalculator1, Calculator1>(Lifetime.Transient); registrar.RegisterType<ICalculator2, Calculator2>(Lifetime.Transient); registrar.RegisterType<ICalculator3, Calculator3>(Lifetime.Transient); var containerWithLoggingInterception = registrar.Build(); containerWithLoggingInterception.AddDecorator(new GriffinLoggingDecorator()); this.containerWithLoggingInterception = containerWithLoggingInterception; }
public void InterfaceToConcrete() { var registrar = new ContainerRegistrar(); registrar.RegisterType(typeof(ISomeDude <>), typeof(SomeDude <>), Lifetime.Transient); registrar.RegisterConcrete <Word>(Lifetime.Transient); var container = registrar.Build(); var actual = container.Resolve <ISomeDude <string> >(); Assert.NotNull(actual); }
private static void RegisterComplex(ContainerRegistrar registrar) { registrar.RegisterType <IFirstService, FirstService>(Lifetime.Singleton); registrar.RegisterType <ISecondService, SecondService>(Lifetime.Singleton); registrar.RegisterType <IThirdService, ThirdService>(Lifetime.Singleton); registrar.RegisterType <ISubObjectOne, SubObjectOne>(Lifetime.Transient); registrar.RegisterType <ISubObjectTwo, SubObjectTwo>(Lifetime.Transient); registrar.RegisterType <ISubObjectThree, SubObjectThree>(Lifetime.Transient); registrar.RegisterType <IComplex, Complex>(Lifetime.Transient); }
private static void RegisterComplex(ContainerRegistrar registrar) { registrar.RegisterType<IFirstService, FirstService>(Lifetime.Singleton); registrar.RegisterType<ISecondService, SecondService>(Lifetime.Singleton); registrar.RegisterType<IThirdService, ThirdService>(Lifetime.Singleton); registrar.RegisterType<ISubObjectOne, SubObjectOne>(Lifetime.Transient); registrar.RegisterType<ISubObjectTwo, SubObjectTwo>(Lifetime.Transient); registrar.RegisterType<ISubObjectThree, SubObjectThree>(Lifetime.Transient); registrar.RegisterType<IComplex, Complex>(Lifetime.Transient); }
public void Should_Resolve_Different_Instances_When_Resolving_Type_Registered_As_Transient_Twice() { // Given var builder = new ContainerRegistrar(); builder.RegisterType <Foo>().Transient(); var container = builder.Build(); // When var first = container.Resolve <Foo>(); var second = container.Resolve <Foo>(); // Then Assert.NotSame(first, second); }
public void Should_Resolve_The_Same_Instance_When_Resolving_Singleton_Twice() { // Given var builder = new ContainerRegistrar(); builder.RegisterType <Foo>().Singleton(); var container = builder.Build(); // When var first = container.Resolve <Foo>(); var second = container.Resolve <Foo>(); // Then Assert.Same(first, second); }
public void Should_be_able_To_take_an_specified_generic_as_a_dependency() { var t = typeof(ISomeDude <>); var t2 = typeof(ISomeDude <string>); var registrar = new ContainerRegistrar(); registrar.RegisterType(typeof(IRestrictedGeneric <SomeClass>), typeof(RestrictedGeneric <SomeClass>), Lifetime.Singleton); registrar.RegisterConcrete <Word>(Lifetime.Transient); registrar.RegisterConcrete <SomeProcessor>(Lifetime.Singleton); var container = registrar.Build(); var actual = container.Resolve <SomeProcessor>(); Assert.NotNull(actual); }
public override void Prepare() { var registrar = new ContainerRegistrar(); RegisterDummies(registrar); RegisterStandard(registrar); RegisterComplex(registrar); this.container = registrar.Build(); registrar = new ContainerRegistrar(); registrar.RegisterType<ICalculator, Calculator>(Lifetime.Transient); var containerWithLoggingInterception = registrar.Build(); containerWithLoggingInterception.AddDecorator(new GriffinLoggingDecorator()); this.containerWithLoggingInterception = containerWithLoggingInterception; }
public override void Prepare() { var registrar = new ContainerRegistrar(); RegisterDummies(registrar); RegisterStandard(registrar); RegisterComplex(registrar); this.container = registrar.Build(); registrar = new ContainerRegistrar(); registrar.RegisterType <ICalculator, Calculator>(Lifetime.Transient); var containerWithLoggingInterception = registrar.Build(); containerWithLoggingInterception.AddDecorator(new GriffinLoggingDecorator()); this.containerWithLoggingInterception = containerWithLoggingInterception; }
public void Prepare() { var registrar = new ContainerRegistrar(); registrar.RegisterType <ISingleton, Singleton>(Lifetime.Singleton); registrar.RegisterType <ITransient, Transient>(Lifetime.Transient); registrar.RegisterType <ICombined, Combined>(Lifetime.Transient); this.container = registrar.Build(); registrar = new ContainerRegistrar(); registrar.RegisterType <ICalculator, Calculator>(Lifetime.Transient); var containerWithLoggingInterception = registrar.Build(); containerWithLoggingInterception.AddDecorator(new GriffinLoggingDecorator()); this.containerWithLoggingInterception = containerWithLoggingInterception; }
private static void RegisterTasks(IContainer container) { // Create a child scope to not affect the underlying // container in case the ICakeTaskFinder references // something that is later replaced. using (var scope = container.BeginLifetimeScope()) { // Find tasks in registered assemblies. var assemblies = scope.Resolve <IEnumerable <Assembly> >(); var finder = scope.Resolve <ICakeTaskFinder>(); var tasks = finder.GetTasks(assemblies); if (tasks.Length > 0) { var registrar = new ContainerRegistrar(); foreach (var task in tasks) { registrar.RegisterType(task).As <IFrostingTask>().Singleton(); } container.Update(registrar); } } }
private static void RegisterStandard(ContainerRegistrar registrar) { registrar.RegisterType <ISingleton, Singleton>(Lifetime.Singleton); registrar.RegisterType <ITransient, Transient>(Lifetime.Transient); registrar.RegisterType <ICombined, Combined>(Lifetime.Transient); }
private static void RegisterDummies(ContainerRegistrar registrar) { registrar.RegisterType<IDummyOne, DummyOne>(Lifetime.Transient); registrar.RegisterType<IDummyTwo, DummyTwo>(Lifetime.Transient); registrar.RegisterType<IDummyThree, DummyThree>(Lifetime.Transient); registrar.RegisterType<IDummyFour, DummyFour>(Lifetime.Transient); registrar.RegisterType<IDummyFive, DummyFive>(Lifetime.Transient); registrar.RegisterType<IDummySix, DummySix>(Lifetime.Transient); registrar.RegisterType<IDummySeven, DummySeven>(Lifetime.Transient); registrar.RegisterType<IDummyEight, DummyEight>(Lifetime.Transient); registrar.RegisterType<IDummyNine, DummyNine>(Lifetime.Transient); registrar.RegisterType<IDummyTen, DummyTen>(Lifetime.Transient); }
private static void RegisterPropertyInjection(ContainerRegistrar registrar) { registrar.RegisterType<IServiceA, ServiceA>(Lifetime.Singleton); registrar.RegisterType<IServiceB, ServiceB>(Lifetime.Singleton); registrar.RegisterType<IServiceC, ServiceC>(Lifetime.Singleton); registrar.RegisterService<ISubObjectA>(x => new SubObjectA { ServiceA = x.Resolve<IServiceA>() }, Lifetime.Transient); registrar.RegisterService<ISubObjectB>(x => new SubObjectB { ServiceB = x.Resolve<IServiceB>() }, Lifetime.Transient); registrar.RegisterService<ISubObjectC>(x => new SubObjectC { ServiceC = x.Resolve<IServiceC>() }, Lifetime.Transient); registrar.RegisterService<IComplexPropertyObject1>( x => new ComplexPropertyObject1 { ServiceA = x.Resolve<IServiceA>(), ServiceB = x.Resolve<IServiceB>(), ServiceC = x.Resolve<IServiceC>(), SubObjectA = x.Resolve<ISubObjectA>(), SubObjectB = x.Resolve<ISubObjectB>(), SubObjectC = x.Resolve<ISubObjectC>() }, Lifetime.Transient); registrar.RegisterService<IComplexPropertyObject2>( x => new ComplexPropertyObject2 { ServiceA = x.Resolve<IServiceA>(), ServiceB = x.Resolve<IServiceB>(), ServiceC = x.Resolve<IServiceC>(), SubObjectA = x.Resolve<ISubObjectA>(), SubObjectB = x.Resolve<ISubObjectB>(), SubObjectC = x.Resolve<ISubObjectC>() }, Lifetime.Transient); registrar.RegisterService<IComplexPropertyObject3>( x => new ComplexPropertyObject3 { ServiceA = x.Resolve<IServiceA>(), ServiceB = x.Resolve<IServiceB>(), ServiceC = x.Resolve<IServiceC>(), SubObjectA = x.Resolve<ISubObjectA>(), SubObjectB = x.Resolve<ISubObjectB>(), SubObjectC = x.Resolve<ISubObjectC>() }, Lifetime.Transient); }
private static void RegisterStandard(ContainerRegistrar registrar) { registrar.RegisterType<ISingleton1, Singleton1>(Lifetime.Singleton); registrar.RegisterType<ISingleton2, Singleton2>(Lifetime.Singleton); registrar.RegisterType<ISingleton3, Singleton3>(Lifetime.Singleton); registrar.RegisterType<ITransient1, Transient1>(Lifetime.Transient); registrar.RegisterType<ITransient2, Transient2>(Lifetime.Transient); registrar.RegisterType<ITransient3, Transient3>(Lifetime.Transient); registrar.RegisterType<ICombined1, Combined1>(Lifetime.Transient); registrar.RegisterType<ICombined2, Combined2>(Lifetime.Transient); registrar.RegisterType<ICombined3, Combined3>(Lifetime.Transient); }
private static void RegisterStandard(ContainerRegistrar registrar) { registrar.RegisterType<ISingleton, Singleton>(Lifetime.Singleton); registrar.RegisterType<ITransient, Transient>(Lifetime.Transient); registrar.RegisterType<ICombined, Combined>(Lifetime.Transient); }
private async void Startup() { // Set the AppDomain working directory to the current resource root Environment.CurrentDirectory = Path.GetFullPath(API.GetResourcePath(API.GetCurrentResourceName())); Logger.Initialize(); new Logger().Info($"NFive {typeof(Program).Assembly.GetCustomAttributes<AssemblyInformationalVersionAttribute>().First().InformationalVersion}"); var config = ConfigurationManager.Load <CoreConfiguration>("nfive.yml"); ServerLogConfiguration.Output = config.Log.Output; //ServerConfiguration.LogLevel = config.Log.Level; var logger = new Logger(config.Log.Core); API.SetGameType(config.Display.Game); API.SetMapName(config.Display.Map); // Setup RPC handlers RpcManager.Configure(config.Log.Rpc, this.EventHandlers); // Client log mirroring new RpcHandler().Event("nfive:log:mirror").On(new Action <IRpcEvent, DateTime, LogLevel, string, string>((e, dt, level, prefix, message) => { new Logger(LogLevel.Trace, $"Client#{e.Client.Handle}|{prefix}").Log(message, level); })); var events = new EventManager(config.Log.Events); var rcon = new RconManager(new RpcHandler()); // Load core controllers var dbController = new DatabaseController(new Logger(config.Log.Core, "Database"), events, new RpcHandler(), rcon, ConfigurationManager.Load <DatabaseConfiguration>("database.yml")); await dbController.Loaded(); this.controllers.Add(new Name("NFive/Database"), new List <Controller> { dbController }); var sessionController = new SessionController(new Logger(config.Log.Core, "Session"), events, new RpcHandler(), rcon, ConfigurationManager.Load <SessionConfiguration>("session.yml")); await sessionController.Loaded(); this.controllers.Add(new Name("NFive/Session"), new List <Controller> { sessionController }); // Resolve dependencies var graph = DefinitionGraph.Load(); var pluginDefaultLogLevel = config.Log.Plugins.ContainsKey("default") ? config.Log.Plugins["default"] : LogLevel.Info; // IoC var assemblies = new List <Assembly>(); assemblies.AddRange(graph.Plugins.Where(p => p.Server?.Include != null).SelectMany(p => p.Server.Include.Select(i => Assembly.LoadFrom(Path.Combine("plugins", p.Name.Vendor, p.Name.Project, $"{i}.net.dll"))))); assemblies.AddRange(graph.Plugins.Where(p => p.Server?.Main != null).SelectMany(p => p.Server.Main.Select(m => Assembly.LoadFrom(Path.Combine("plugins", p.Name.Vendor, p.Name.Project, $"{m}.net.dll"))))); var registrar = new ContainerRegistrar(); registrar.RegisterService <ILogger>(s => new Logger()); registrar.RegisterType <IRpcHandler, RpcHandler>(); registrar.RegisterInstance <IEventManager>(events); registrar.RegisterInstance <IRconManager>(rcon); registrar.RegisterInstance <IClientList>(new ClientList(new Logger(config.Log.Core, "ClientList"), new RpcHandler())); registrar.RegisterSdkComponents(assemblies.Distinct()); // DI var container = registrar.Build(); // Load plugins into the AppDomain foreach (var plugin in graph.Plugins) { logger.Info($"Loading {plugin.FullName}"); // Load include files foreach (var includeName in plugin.Server?.Include ?? new List <string>()) { var includeFile = Path.Combine("plugins", plugin.Name.Vendor, plugin.Name.Project, $"{includeName}.net.dll"); if (!File.Exists(includeFile)) { throw new FileNotFoundException(includeFile); } AppDomain.CurrentDomain.Load(File.ReadAllBytes(includeFile)); } // Load main files foreach (var mainName in plugin.Server?.Main ?? new List <string>()) { var mainFile = Path.Combine("plugins", plugin.Name.Vendor, plugin.Name.Project, $"{mainName}.net.dll"); if (!File.Exists(mainFile)) { throw new FileNotFoundException(mainFile); } var types = Assembly.LoadFrom(mainFile).GetTypes().Where(t => !t.IsAbstract && t.IsClass).ToList(); // Find migrations foreach (var migrationType in types.Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(MigrationConfiguration <>))) { var configuration = (DbMigrationsConfiguration)Activator.CreateInstance(migrationType); var migrator = new DbMigrator(configuration); if (!migrator.GetPendingMigrations().Any()) { continue; } if (!ServerConfiguration.AutomaticMigrations) { throw new MigrationsPendingException($"Plugin {plugin.FullName} has pending migrations but automatic migrations are disabled"); } foreach (var migration in migrator.GetPendingMigrations()) { new Logger(config.Log.Core, "Database").Debug($"[{mainName}] Running migration: {migration}"); migrator.Update(migration); } } // Find controllers foreach (var controllerType in types.Where(t => t.IsSubclassOf(typeof(Controller)) || t.IsSubclassOf(typeof(ConfigurableController <>)))) { var logLevel = config.Log.Plugins.ContainsKey(plugin.Name) ? config.Log.Plugins[plugin.Name] : pluginDefaultLogLevel; var constructorArgs = new List <object> { new Logger(logLevel, plugin.Name), events, new RpcHandler(), rcon }; // Check if controller is configurable if (controllerType.BaseType != null && controllerType.BaseType.IsGenericType && controllerType.BaseType.GetGenericTypeDefinition() == typeof(ConfigurableController <>)) { // Initialize the controller configuration constructorArgs.Add(ConfigurationManager.InitializeConfig(plugin.Name, controllerType.BaseType.GetGenericArguments()[0])); } // Resolve IoC arguments constructorArgs.AddRange(controllerType.GetConstructors()[0].GetParameters().Skip(constructorArgs.Count).Select(p => container.Resolve(p.ParameterType))); Controller controller = null; try { // Construct controller instance controller = (Controller)Activator.CreateInstance(controllerType, constructorArgs.ToArray()); } catch (Exception ex) { // TODO: Dispose of controller logger.Error(ex, $"Unhandled exception in plugin {plugin.FullName}"); } if (controller == null) { continue; } try { await controller.Loaded(); if (!this.controllers.ContainsKey(plugin.Name)) { this.controllers.Add(plugin.Name, new List <Controller>()); } this.controllers[plugin.Name].Add(controller); } catch (Exception ex) { // TODO: Dispose of controller logger.Error(ex, $"Unhandled exception loading plugin {plugin.FullName}"); } } } } #pragma warning disable 4014 foreach (var controller in this.controllers.SelectMany(c => c.Value)) { controller.Started(); } #pragma warning restore 4014 rcon.Controllers = this.controllers; new RpcHandler().Event(SDK.Core.Rpc.RpcEvents.ClientPlugins).On(e => e.Reply(graph.Plugins)); events.Raise(ServerEvents.ServerInitialized); logger.Debug($"{graph.Plugins.Count} plugin(s) loaded, {this.controllers.Count} controller(s) created"); }