public void OwnedLazyMetaTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<DisposableService>().As<IDisposableService>().WithMetadata( "Hello", "World")); Owned<Lazy<Meta<IDisposableService>>> ownedLazy = container.Locate<Owned<Lazy<Meta<IDisposableService>>>>(); Assert.NotNull(ownedLazy); Assert.NotNull(ownedLazy.Value); Assert.NotNull(ownedLazy.Value.Value); Assert.NotNull(ownedLazy.Value.Value.Value); bool disposedCalled = false; ownedLazy.Value.Value.Value.Disposing += (sender, args) => disposedCalled = true; ownedLazy.Dispose(); Assert.True(disposedCalled); KeyValuePair<string, object> metadata = ownedLazy.Value.Value.Metadata.First(); Assert.Equal("Hello", metadata.Key); Assert.Equal("World", metadata.Value); }
public void BulkLocateWithKey() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export(Types.FromThisAssembly()) .ByInterface<ISimpleObject>() .WithKey(t => t.Name.Last())); container.Configure(c => { foreach (char ch in "ABCDE") { c.Export<ImportSingleSimpleObject>() .WithKey(ch) .WithCtorParam<ISimpleObject>() .LocateWithKey(ch); } }); ImportSingleSimpleObject single = container.Locate<ImportSingleSimpleObject>(withKey: 'A'); Assert.NotNull(single); Assert.IsType<SimpleObjectA>(single.SimpleObject); Assert.Equal(3, container.LocateAll<ImportSingleSimpleObject>(withKey: new[] { 'A', 'C', 'E' }).Count); }
public void FactoryFiveArgWithOutBasicAndOutOfOrderTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); BasicService basicService = new BasicService(); container.Configure(c => { c.Export<FiveArgParameterService>().As<IArrayOfObjectsPropertyService>(); c.ExportInstance(basicService).As<IBasicService>(); }); FiveArgParameterService.ActivateWithOutBasicServiceAndOutOfOrder factory = container.Locate<FiveArgParameterService.ActivateWithOutBasicServiceAndOutOfOrder>(); Assert.NotNull(factory); IArrayOfObjectsPropertyService instance = factory(14.0m, "Blah", 9.0, 5); Assert.NotNull(instance); Assert.Equal(5, instance.Parameters.Length); Assert.Equal("Blah", instance.Parameters[0]); Assert.Equal(5, instance.Parameters[1]); Assert.Equal(9.0, instance.Parameters[2]); Assert.Equal(14.0m, instance.Parameters[3]); Assert.Equal(basicService, instance.Parameters[4]); }
/// <summary> /// Configures the default dependencies. /// </summary> /// <param name="dependencyInjectionContainer">The dependency injection container.</param> public void ConfigureDefaultDependencies(DependencyInjectionContainer dependencyInjectionContainer) { ExceptionUtilities.CheckArgumentNotNull(dependencyInjectionContainer, "dependencyInjectionContainer"); foreach (var param in this.TestParameters) { dependencyInjectionContainer.TestParameters[param.Key] = param.Value; } // set up dependency injector dependencyInjectionContainer.RegisterCustomResolver(typeof(Logger), this.GetLoggerForType).Transient(); dependencyInjectionContainer.RegisterInstance<IDependencyInjector>(dependencyInjectionContainer); dependencyInjectionContainer.InjectDependenciesInto(dependencyInjectionContainer); dependencyInjectionContainer.InjectDependenciesInto(this.implementationSelector); this.implementations = this.implementationSelector.GetImplementations(this.TestParameters).ToList(); // only register dependencies that cannot already be resolved (unless the dependency was specified as a // test parameter, in which case override the default) foreach (var implInfo in this.implementations.Where(i => i.IsTestParameterSpecified || !dependencyInjectionContainer.CanResolve(i.ContractType))) { var options = dependencyInjectionContainer.Register(implInfo.ContractType, implInfo.ImplementationType); options.IsTransient = implInfo.IsTransient; } }
public void CombinedSpecialTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<LazyService>().As<ILazyService>().WithMetadata("Hello", "World")); LazyService.Created = false; Lazy<Meta<ILazyService>> lazy = container.Locate<Lazy<Meta<ILazyService>>>(); Assert.NotNull(lazy); Assert.False(LazyService.Created); Assert.NotNull(lazy.Value); Assert.NotNull(lazy.Value.Value); ILazyService service = lazy.Value.Value; Assert.NotNull(service); Assert.True(LazyService.Created); KeyValuePair<string, object> metadata = lazy.Value.Metadata.First(); Assert.Equal("Hello", metadata.Key); Assert.Equal("World", metadata.Value); }
static int Main(string[] args) { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export(Types.FromThisAssembly()). ByInterface(typeof(IExampleModule)). ByInterface(typeof(IExampleSubModule<>)). ByInterface(typeof(IExample<>))); IEnumerable<IExampleModule> exampleModules = container.LocateAll<IExampleModule>(); try { foreach (IExampleModule exampleModule in exampleModules) { exampleModule.Execute(); } } catch (Exception exp) { Console.WriteLine("Exception thrown"); Console.WriteLine(exp.Message); return -1; } return 0; }
public void BeginLifetimeScope() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<DisposableService>().As<IDisposableService>().Lifestyle.SingletonPerScope()); IDisposableService service = container.Locate<IDisposableService>(); Assert.NotNull(service); bool called = false; using (var scope = container.BeginLifetimeScope()) { var secondService = scope.Locate<IDisposableService>(); Assert.NotNull(secondService); Assert.NotSame(service, secondService); Assert.Same(secondService, scope.Locate<IDisposableService>()); secondService.Disposing += (sender, args) => called = true; } Assert.True(called); }
public void ImportIInjectionScopeDiagnostic() { DependencyInjectionContainer container = new DependencyInjectionContainer(); InjectionScopeDiagnostic diag = container.Locate<InjectionScopeDiagnostic>(); Assert.Equal(0, diag.PossibleMissingDependencies.Count()); }
public GraceServiceLocator(DependencyInjectionContainer container) { if (container == null) { throw new ArgumentNullException("container"); } this.container = container; }
/// <summary> /// Configures the dependencies for the test case. /// </summary> /// <param name="container">The container (private to the test case).</param> protected override void ConfigureDependencies(DependencyInjectionContainer container) { base.ConfigureDependencies(container); #if WINDOWS_PHONE container.Register<IAuthenticationProvider, AnonymousAuthenticationProvider>(); #endif AstoriaTestServices.ConfigureDependencies(container); }
/// <summary> /// Default constructor /// </summary> /// <param name="container">container for the kernel manager</param> /// <param name="comparer">used to compare to export strategies for which one should be used</param> /// <param name="blackList">export strategy black list</param> public InjectionKernelManager(DependencyInjectionContainer container, ExportStrategyComparer comparer, BlackList blackList) { Container = container; this.comparer = comparer; this.blackList = blackList; }
public void AutoCreateTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<BasicService>().As<IBasicService>()); ImportConstructorService constructorService = container.Locate<ImportConstructorService>(); Assert.NotNull(constructorService); }
public void ConfigureWithXmlExportTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.ConfigureWithXml(); IConstructorImportService importService = container.Locate<IConstructorImportService>(); Assert.NotNull(importService); }
public void ConfigureWithXmlModulePropertySetTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.ConfigureWithXml(); int intProperty = (int)container.Locate("IntProperty"); Assert.Equal(5, intProperty); }
public void ConfigureWithXmlModuleTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.ConfigureWithXml(); IBasicService basicService = container.Locate<IBasicService>(); Assert.NotNull(basicService); }
private static IDependencyInjectionContainer CreateDIContainer() { var container = new DependencyInjectionContainer { ThrowExceptions = false }; container.Configure( registration => registration .Export<PeopleService>() .As<IPeopleService>()); return container; }
public override void Dispose() { // Allow the container and everything it references to be garbage collected. if (this.container == null) { return; } this.container.Dispose(); this.container = null; }
public void InEnvironment() { DependencyInjectionContainer container = new DependencyInjectionContainer(ExportEnvironment.UnitTest); container.Configure(c => c.ExportAssembly(GetType().Assembly).InEnvironment(ExportEnvironment.RunTimeOnly)); IEnumerable<ISimpleObject> simpleObjects = container.LocateAll<ISimpleObject>(); Assert.NotNull(simpleObjects); Assert.Equal(0, simpleObjects.Count()); }
public void SelectTypes() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure( c => c.ExportAssembly(GetType().Assembly).ByInterface(typeof(ISimpleObject)).Select(TypesThat.EndWith("C"))); IEnumerable<ISimpleObject> simpleObjects = container.LocateAll<ISimpleObject>(); Assert.NotNull(simpleObjects); Assert.Equal(1, simpleObjects.Count()); }
public void DebugConsoleLog() { Logger.SetLogService(new DebugConsoleLogService()); DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export<BasicService>().As<IBasicService>()); IBasicService basicService = container.Locate<IBasicService>(); Assert.NotNull(basicService); }
public void ConfigureWithXmlThirdSectionWithShortNames() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.ConfigureWithXml("thirdGrace"); IConstructorImportService importService = container.Locate<IConstructorImportService>(); Assert.NotNull(importService); Assert.Equal(5, container.Locate("IntProperty")); }
public void ExportInterfaces() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure( c => c.ExportAssembly(GetType().Assembly).ByInterfaces(t => t.Name.StartsWith("ISimple"))); IEnumerable<ISimpleObject> simpleObjects = container.LocateAll<ISimpleObject>(); Assert.NotNull(simpleObjects); Assert.Equal(5, simpleObjects.Count()); }
public void BasedOnInterfaceByType() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export(Types.FromThisAssembly()) .BasedOn<ISimpleObject>() .ByType()); SimpleObjectA simpleObjectA = container.Locate<SimpleObjectA>(); Assert.NotNull(simpleObjectA); }
public void SubstituteMultiple() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Substitute(); container.Configure(c => c.Export<ImportIEnumerableService>().As<IImportIEnumerableService>()); IImportIEnumerableService iEnumerableService = container.Locate<IImportIEnumerableService>(); Assert.NotNull(iEnumerableService); Assert.Equal(1, iEnumerableService.Count); }
public void AsKeyedStringTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => { c.ExportInstance((scope, context) => "Hello"); c.ExportInstance((scope, context) => "HelloAgain").AsKeyed<string,string>("Key"); }); Assert.Equal("Hello",container.Locate<string>()); Assert.Equal("HelloAgain",container.Locate<string>(withKey: "Key")); }
public void SimpleExample() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Substitute(); container.Configure(c => c.Export<ImportConstructor>()); IImportConstructor constructor = container.Locate<IImportConstructor>(); Assert.NotNull(constructor); Assert.NotNull(constructor.BasicService); }
public void BlackOutListTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.BlackListExportType(typeof(BasicService)); container.Configure( ioc => ioc.Export<BasicService>().As<IBasicService>()); IBasicService basicService = container.Locate<IBasicService>(); Assert.Null(basicService); }
public void BulkLifestyleSingleton() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export(Types.FromThisAssembly()) .ByInterface<IBasicService>() .Lifestyle.Singleton()); IBasicService basicService = container.Locate<IBasicService>(); Assert.NotNull(basicService); Assert.Same(basicService, container.Locate<IBasicService>()); }
public void BasedOnInterfaceTest() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Configure(c => c.Export(Types.FromThisAssembly()) .BasedOn<ISimpleObject>() .ByInterfaces()); IEnumerable<ISimpleObject> simpleObjects = container.LocateAll<ISimpleObject>(); Assert.NotNull(simpleObjects); Assert.Equal(5, simpleObjects.Count()); }
public void MoqExtension() { DependencyInjectionContainer container = new DependencyInjectionContainer(); container.Moq(); container.Configure(c => c.Export<ImportConstructor>()); ImportConstructor importConstructor = container.Locate<ImportConstructor>(); Assert.NotNull(importConstructor); Assert.NotNull(importConstructor.BasicService); }
public void ExportInstance_With_Scope() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.ExportInstance(scope => new BasicService { Count = 5 }).As <IBasicService>(); c.Export <ConstructorImportService>().As <IConstructorImportService>(); }); var service = container.Locate <IConstructorImportService>(); Assert.NotNull(service); Assert.Equal(5, service.BasicService.Count); }
public void Container_Match_Best_Constructor_Two_Args() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <MultipleConstructorImport>(); c.Export <BasicService>().As <IBasicService>(); c.Export <ConstructorImportService>().As <IConstructorImportService>(); }); var service = container.Locate <MultipleConstructorImport>(); Assert.NotNull(service); Assert.NotNull(service.BasicService); Assert.NotNull(service.ConstructorImportService); }
public static void Exec() { //容器 var container = new DependencyInjectionContainer(); container.Configure(m => { //这里演示如何简单注册同一个接口对应其实现 m.Export <AccountRepository>().As <IAccountRepository>(); m.Export <AccountService>().As <IAccountService>(); //这里演示如何使用键值注册同一个接口的多个实现 m.Export <UserRepositoryA>().AsKeyed <IUserRepository>("A"); //这里同时演示使用带参数构造器来键值注册 m.Export <UserRepositoryB>().AsKeyed <IUserRepository>("B").WithCtorParam <string>(() => { return("kkkkk"); }); //这里演示依赖倒置而使用构造器带键值注入 m.Export <UserService>().As <IUserService>().WithCtorParam <IUserRepository>().LocateWithKey("B"); m.Export <MultipleConstructorImportService>().As <IMultipleConstructorImportService>(); }); //获取简单注册实例 var accountRepo = container.Locate <IAccountRepository>(); Console.WriteLine(accountRepo.Get());//输出:[Account]简单注册调用[Repo] var accountSvc = container.Locate <IAccountService>(); Console.WriteLine(accountSvc.Get());//输出:[Account]简单注册调用[Repo][Service] Console.WriteLine(); //获取指定键值的实例 var userRepo = container.Locate <IUserRepository>(withKey: "A"); Console.WriteLine(userRepo.Get()); //输出:[User]键值注册调用A[Repo] var userSvc = container.Locate <IUserService>(); //输出:Ctor param1:kkkkk Console.WriteLine(userSvc.Get()); //输出:[User]键值注册调用B[Repo][Service] Console.WriteLine(); //这里演示多个构造函数注入 var multipleConstructorImportSvc = container.Locate <IMultipleConstructorImportService>(); }
public void Container_LocateAll_Keyed_Return() { var container = new DependencyInjectionContainer(c => c.ReturnKeyedInEnumerable = true); container.Configure(c => { c.Export <MultipleService1>().AsKeyed <IMultipleService>(1); c.Export <MultipleService2>().AsKeyed <IMultipleService>(2); c.Export <MultipleService3>().AsKeyed <IMultipleService>(3); }); var enumerable = container.LocateAll(typeof(IMultipleService)); Assert.Equal(3, enumerable.Count); Assert.IsType <MultipleService1>(enumerable[0]); Assert.IsType <MultipleService2>(enumerable[1]); Assert.IsType <MultipleService3>(enumerable[2]); }
public void Generic_Dependent_Constraints() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <MultipleService1>().As <IMultipleService>(); c.Export <BasicService>().As <IBasicService>(); c.Export(typeof(GenericConstraintServiceA <>)).As(typeof(IGenericConstraintService <>)); c.Export(typeof(GenericConstraintBasicService <>)).As(typeof(IGenericConstraintService <>)); }); var instance = container.Locate <DependentService <IGenericConstraintService <IMultipleService> > >(); Assert.NotNull(instance); Assert.NotNull(instance.Value); Assert.IsType <GenericConstraintServiceA <IMultipleService> >(instance.Value); }
public void DynamicMethod_2_Constant() { var container = new DependencyInjectionContainer(GraceDynamicMethod.Configuration(c => { c.Trace = s => Assert.DoesNotContain("falling back", s); })); container.Configure(c => { c.Export <Dependent2>(). WithCtorParam <IBasicService>(() => new BasicService()).Named("basicService1"). WithCtorParam <IBasicService>(() => new BasicService()).Named("basicService2"); }); var instance = container.Locate <Dependent2>(); Assert.NotNull(instance); }
public void ThrowsExceptionWhenResolvingTypeWithUnregisteredDependency() { // arrange var container = new DependencyInjectionContainer(); container.Register <B, B>(); // act try { var b = container.Resolve <B>(); Assert.True(false, $"Type {typeof(B)} has an unregistered dependency, so we should not be able to resolve it from the container."); } catch (TypeNotRegisteredException) { // Do nothing because this is exactly what we wanted. } }
private static IMediator BuildMediator(WrappingWriter writer) { var container = new DependencyInjectionContainer(); container.Configure(c => { c.ExportFunc <ServiceFactory>(scope => scope.Locate); c.ExportInstance <TextWriter>(writer); //Pipeline works out of the box here c.ExportAssemblies( new[] { typeof(IMediator).Assembly, typeof(Ping).Assembly }) .ByInterfaces(); }); return(container.Locate <IMediator>()); }
public void DynamicFactoryStrategy_ExportFactoryTwoInt_UnnamedOrdered() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export(typeof(IntDependantClass)).As(typeof(IIntDependantClass)); c.ExportFactory <IIntDependantClassUnnamedOrderedProvider>(); }); var factory = container.Locate <IIntDependantClassUnnamedOrderedProvider>(); var instance = factory.Create(15, 20); Assert.NotNull(instance); Assert.Equal(15, instance.A); Assert.Equal(20, instance.B); }
public void Singleton_Attribute_Test() { var container = new DependencyInjectionContainer(); container.Configure(c => c.ExportAssemblyContaining <ExportAttributeTests>(). ExportAttributedTypes(). Where(TypesThat.AreInTheSameNamespaceAs <TestAttribute>())); var instance = container.Locate <IAttributedSingletonService>(); Assert.NotNull(instance); var instance2 = container.Locate <IAttributedSingletonService>(); Assert.NotNull(instance2); Assert.Same(instance, instance2); }
protected override void ConfigureServices(DependencyInjectionContainer container) { var mapper = new MapperConfiguration(x => { x.ConstructServicesUsing(container.Locate); x.CreateMap <Item, ItemViewModel>(); }).CreateMapper(); container.Configure(c => { c.ExportInstance(mapper).As <IMapper>(); c.Export <InterfaceNamingConvention>().As <INamingConventionService>(); }); var uri = GetServiceUri(); container.ProxyNamespace(uri, namespaces: typeof(Anchor).Namespace); }
public void KeyedLocateDelegate_Create() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <SimpleObjectA>().AsKeyed <ISimpleObject>("A"); c.Export <SimpleObjectB>().AsKeyed <ISimpleObject>("B"); }); var keyedDelegate = container.Locate <KeyedLocateDelegate <string, ISimpleObject> >(); var instanceA = keyedDelegate("A"); var instanceB = keyedDelegate("B"); Assert.IsType <SimpleObjectA>(instanceA); Assert.IsType <SimpleObjectB>(instanceB); }
public void Meta_Enumerator() { var container = new DependencyInjectionContainer(); container.Configure(c => c.Export <BasicService>().As <IBasicService>().WithMetadata("Hello", "World")); var meta = container.Locate <Meta <IBasicService> >(); Assert.NotNull(meta); Assert.Equal(1, meta.Metadata.Count); Assert.Equal(1, meta.Metadata.Count()); Assert.Equal(1, ((IEnumerable)meta.Metadata).OfType <KeyValuePair <object, object> >().Count()); var data = meta.Metadata.First(); Assert.Equal("Hello", data.Key); Assert.Equal("World", data.Value); }
public void ConventionBasedNameTest() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.AddInjectionValueProvider(new ConventionBasedValueProvider()); c.Export <MultipleService1>().AsKeyed <IMultipleService>("serviceA"); c.Export <MultipleService2>().AsKeyed <IMultipleService>("serviceB"); c.Export(typeof(ConventionBasedRegistrationTest).Assembly.ExportedTypes).ByInterfaces(); }); var instance = container.Locate <IConventionBasedService>(); Assert.NotNull(instance); Assert.IsType <MultipleService1>(instance.ServiceA); Assert.IsType <MultipleService2>(instance.ServiceB); }
public void Dynamic_WithCtorValue() { var container = new DependencyInjectionContainer(c => c.Behaviors.ConstructorSelection = ConstructorSelectionMethod.Dynamic); container.Configure(c => c.Export <MultipleConstructorImport>().WithCtorParam(() => new BasicService())); var instance = container.Locate <MultipleConstructorImport>(); Assert.NotNull(instance); Assert.NotNull(instance.BasicService); Assert.Null(instance.ConstructorImportService); instance = container.Locate <MultipleConstructorImport>(new ConstructorImportService(new BasicService())); Assert.NotNull(instance); Assert.NotNull(instance.BasicService); Assert.NotNull(instance.ConstructorImportService); }
public void DynamicMethod_MemberInit_Test() { var container = new DependencyInjectionContainer(GraceDynamicMethod.Configuration(c => { c.Trace = s => Assert.DoesNotContain("falling back", s); })); container.Configure(c => { c.Export <BasicService>().As <IBasicService>(); c.Export <PropertyInjectionService>().As <IPropertyInjectionService>().ImportProperty(i => i.BasicService); }); var instance = container.Locate <IPropertyInjectionService>(); Assert.NotNull(instance); Assert.NotNull(instance.BasicService); }
public void Dynamic_Constructor_Parameter_Missing_Throws() { var container = new DependencyInjectionContainer(); container.Configure(c => c.Export(typeof(DependentService <>)).As(typeof(IDependentService <>)).WithCtorParam <object>().IsDynamic()); using (var childScope = container.CreateChildScope()) { Assert.Throws <LocateException>(() => childScope.Locate <IDependentService <IBasicService> >()); childScope.Configure(c => c.Export <BasicService>().As <IBasicService>()); var instance = childScope.Locate <IDependentService <IBasicService> >(); Assert.NotNull(instance); Assert.NotNull(instance.Value); } }
public void Encrichment_Executes() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <BasicService>().As <IBasicService>().EnrichWithDelegate((scope, context, service) => { service.Count = 5; return(service); }); }); var instance = container.Locate <IBasicService>(); Assert.NotNull(instance); Assert.Equal(5, instance.Count); }
public void Locate_Open_Generic_Filtered() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export(typeof(DependentService <>)).WithCtorParam <object>().Named("value").Consider(s => s.ActivationType.Name.EndsWith("B`1")); c.Export(typeof(GenericClassA <>)).As(typeof(IGenericClass <>)); c.Export(typeof(GenericClassB <>)).As(typeof(IGenericClass <>)); c.Export(typeof(GenericClassC <>)).As(typeof(IGenericClass <>)); }); var instance = container.Locate <DependentService <IGenericClass <int> > >(); Assert.NotNull(instance); Assert.NotNull(instance.Value); Assert.IsType <GenericClassB <int> >(instance.Value); }
public void FluentExportStrategyConfigurationGeneric_ImportConstructorMethod() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <BasicService>().ByInterfaces(); c.Export <ConstructorImportService>().As <IConstructorImportService>(); c.Export <MultipleConstructorImport>() .ImportConstructor(() => new MultipleConstructorImport(Arg.Any <IBasicService>())); }); var instance = container.Locate <MultipleConstructorImport>(); Assert.NotNull(instance); Assert.NotNull(instance.BasicService); Assert.Null(instance.ConstructorImportService); }
public void MethodInjection_Inject_Members_That_Are_Method_With_Filter() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <BasicService>().As <IBasicService>(); c.Export <MethodInjectionClass>().ImportMembers(MembersThat.AreMethod(m => m.Name.StartsWith("Some")), true); }); var instance = container.Locate <MethodInjectionClass>(); Assert.NotNull(instance); Assert.Null(instance.BasicService); Assert.NotNull(instance.SecondService); Assert.IsType <BasicService>(instance.SecondService); }
private static void ConfigureList(CommandLineBuilder builder, DependencyInjectionContainer container) { var listCommand = new Command("list") { new Argument <ListType>("listType") }; listCommand.Handler = CommandHandler.Create((ListType listType) => { container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(new Dictionary <string, object>())) .As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); deployer.ListFunctions(); }); builder.AddCommand(listCommand); }
static int Main() { // TODO: Migrate to Main async method with C# 7.1 BitResult result = null; try { var container = DependencyInjectionContainer.BuildDefault(); var program = new Program(container); var task = program.Run(); task.Wait(); if (!task.IsCompletedSuccessfully) { throw task.Exception; } result = task.Result; } catch (Exception exception) { result = new BitResult { ResultCode = exception.HResult, ResultMessage = exception.Message }; } finally { if (result == null) { result = new BitResult { ResultCode = -1, ResultMessage = "Fatal unespected exception." }; } } // TODO: Print messages return(result.ResultCode); }
public void Container_BeginLifetimeScope_Locate_ExportLocatorScope() { var container = new DependencyInjectionContainer(); container.Configure(c => c.Export <DependentService <IExportLocatorScope> >().Lifestyle.SingletonPerScope()); using (var scope1 = container.BeginLifetimeScope()) { using (var scope2 = container.BeginLifetimeScope()) { var instance1 = scope1.Locate <DependentService <IExportLocatorScope> >(); var instance2 = scope2.Locate <DependentService <IExportLocatorScope> >(); Assert.NotNull(instance1); Assert.NotNull(instance2); Assert.NotSame(instance1, instance2); } } }
public void Container_BeginLifetimeScope_DisposeCorrectly() { var container = new DependencyInjectionContainer(); container.Configure(c => c.Export <DisposableService>().As <IDisposableService>()); var disposedCalled = false; using (var lifetimeScope = container.BeginLifetimeScope()) { var disposed = lifetimeScope.Locate <IDisposableService>(); Assert.NotNull(disposed); disposed.Disposing += (sender, args) => disposedCalled = true; } Assert.True(disposedCalled); }
public void MultipleResolvesWithDifferentConstructedTypes() { var containerServices = new ContainerServicesBuilder().DisallowAutomaticRegistrations() .Build(); var container = new DependencyInjectionContainer(containerServices).Register(typeof(ObservableCollection <>), options => options.UseDefaultConstructor() .UseScopedLifetime() .MapToAbstractions(typeof(IList <>))) .Register(typeof(GenericTypeWithDependencyToOtherGenericType <>)); using (var childContainer = container.CreateChildContainer()) { var instance1 = childContainer.Resolve <GenericTypeWithDependencyToOtherGenericType <string> >(); instance1.Collection.Should().BeOfType <ObservableCollection <string> >(); var instance2 = childContainer.Resolve <GenericTypeWithDependencyToOtherGenericType <int> >(); instance2.Collection.Should().BeOfType <ObservableCollection <int> >(); } }
public void MultipleDecoratorWithMultipleConstructorParameters() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.Export <BasicService>().As <IBasicService>(); c.Export <CommandA>().As <ICommand <int> >(); c.Export <OtherCommand>().As <ICommand <int> >(); c.ExportDecorator(typeof(ValidatingCommand <>)).As(typeof(ICommand <>)); c.ExportDecorator(typeof(LoggingComand <>)).As(typeof(ICommand <>)); }); var instances = container.Locate <List <ICommand <int> > >(); Assert.Equal(2, instances.Count); Assert.IsType <LoggingComand <int> >(instances[0]); Assert.IsType <LoggingComand <int> >(instances[1]); }
public void ExportTypeSet_USingLifestyle() { var container = new DependencyInjectionContainer(); container.Configure(c => { c.ExportAssemblyContaining <IMultipleService>().ByInterfaces().UsingLifestyle(new SingletonLifestyle()); }); var basicService = container.Locate <IBasicService>(); Assert.Same(basicService, container.Locate <IBasicService>()); var multipleService = container.Locate <IMultipleService>(); Assert.Same(multipleService, container.Locate <IMultipleService>()); Assert.Same(basicService, container.Locate <IBasicService>()); }
public void OptionalBasicServiceWithKeyAndNotIsSatisfied() { var container = new DependencyInjectionContainer(); container.Configure(c => { var optionalStrategy = new OptionalWrapperStrategy(c.OwningScope); c.AddActivationStrategy(optionalStrategy); c.AddMissingDependencyExpressionProvider(optionalStrategy); }); var instance = container.Locate <Optional <IBasicService> >(withKey: "basic"); Assert.False(instance.IsSatisfied()); var value = instance.Value; Assert.Null(value); }
public IServiceCollection Bootstrap() { var ioc = new DependencyInjectionContainer(); var collection = ioc.Create(); collection.AddModule(new InfrastructureModule()); collection.AddModule(new AntlrModule()); collection.AddModule(new EntitiesModule()); collection.AddModule(new OrchestrationModule()); collection.AddModule(new UiModule()); collection.AddTransient( typeof(IQuestionnaireViewModel), typeof(QuestionnaireViewModel)); collection.AddSingleton( typeof(IQuestionnaireDataProvider), typeof(QuestionnaireDataProvider)); return(collection); }