Exemplo n.º 1
2
        private static void ConfigureContainer()
        {
            Container = new Container();

            // Basic test first
            Container.Register<IClient, TestClient>();

            // Singletons can be set up using Reuse - demo this by getting an instance, updating value, then resolving a new instance
            Container.Register<ISingletonClient, SingletonClient>(Reuse.Singleton);

            // Registering with a primitive type to be passed to constructor
            Container.Register<IServiceWithParameter, ServiceWithParameter>(Made.Of(() => new ServiceWithParameter(Arg.Index<string>(0)), requestIgnored => "this is the parameter"));

            // Then registering a complex object instance to be used
            Container.Register<TestObject>();
            var testObj = new TestObject
            {
                ObjectName = "Ian",
                ObjectType = "Person"
            };
            // Register the instance above (into the container) - giving it an Id ("serviceKey") = "obj1"
            Container.RegisterInstance<TestObject>(testObj, serviceKey: "obj1");
            // Register ServiceWithTypeParameter - saying "When you make me a ServiceWithTypeParameter; and a contructor needs a TestObject - use the one with Id "obj1"
            Container.Register<IServiceWithTypeParameter, ServiceWithTypeParameter>(made: Parameters.Of.Type<TestObject>(serviceKey: "obj1"));

            // And finally multiple implementations
            // Registering multiple interface implementations using an enum key
            Container.Register<IMultipleImplementations, MultipleImplementationOne>(serviceKey: InterfaceKey.FirstKey);
            Container.Register<IMultipleImplementations, MultipleImplementationTwo>(serviceKey: InterfaceKey.SecondKey);
        }
Exemplo n.º 2
0
Arquivo: App.cs Projeto: rdavisau/tbc
        public IContainer CreateContainer()
        {
            var assemblies = new List <Assembly>()
            {
                GetType().Assembly
            };

            var container = new DryIoc.Container(rules =>
            {
                rules.WithoutThrowOnRegisteringDisposableTransient()
                .WithAutoConcreteTypeResolution()
                .With(FactoryMethod.ConstructorWithResolvableArguments)
                .WithoutThrowOnRegisteringDisposableTransient()
                .WithFuncAndLazyWithoutRegistration()
                .WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Replace);

                if (Device.RuntimePlatform == Device.iOS)
                {
                    rules = rules.WithoutFastExpressionCompiler();
                }

                return(rules);
            });

            SetupLogging(container);
            RegisterPages(container, assemblies);
            RegisterServices(container, assemblies);
            RegisterViewModels(container, assemblies);

            container.Register <IReloadManager, ReloadManager>();

            return(container);
        }
Exemplo n.º 3
0
 /// <summary>
 ///     Initialisiert den UI Bootloader
 /// </summary>
 /// <param name="container"></param>
 /// <returns></returns>
 public static Container Init(Container container)
 {
     SetupViews(container);
     SetupViewModels(container);
     SetupViewCommands(container);
     return container;
 }
Exemplo n.º 4
0
        public void test_lazy_resolve_and_resolutionscope_reuse()
        {
            var container = new Container();

            container.Register <Component>(Reuse.InResolutionScope);
            container.Register <CreationContext>(Reuse.InResolutionScope);
            container.Register <Factory>(Reuse.Transient);

            var object1  = new object();
            var factory1 = container.Resolve <Factory>();

            factory1.Parameter = object1;

            var object2  = new object();
            var factory2 = container.Resolve <Factory>();

            factory2.Parameter = object2;


            var component1 = factory1.CreateComponent();
            var component2 = factory2.CreateComponent();

            Assert.AreSame(component1.Parameter, object1);
            Assert.AreNotSame(component1.Parameter, component2.Parameter);
        }
Exemplo n.º 5
0
        public void ShellPagedViewModel_Markup_Returns_ActualViewModel()
        {
            var container = new Container();
            var app       = new Application();

            ZeroApp
            .On(app)
            .WithContainer(DryIocZeroContainer.Build(container))
            .RegisterShell(() => new FirstShell())
            .Start();

            var firstPage = container.Resolve <FirstPage>();

            var markup = new ShellPagedViewModelMarkup()
            {
                ViewModel = typeof(FirstViewModel),
                Page      = firstPage
            };

            var provider = new XamlServiceProvider();

            var vmValue = (FirstViewModel)markup.ProvideValue(provider);

            Assert.AreEqual(typeof(FirstViewModel), vmValue.GetType());
            Assert.AreEqual(vmValue, container.Resolve <FirstViewModel>());
        }
Exemplo n.º 6
0
        public async Task Push_And_Prepare_Model(string stringValue)
        {
            var container = new Container();
            var app       = new Application();

            ZeroApp
            .On(app)
            .WithContainer(DryIocZeroContainer.Build(container))
            .RegisterShell(() => new FirstShell())
            .Start();

            var firstViewModel  = container.Resolve <FirstViewModel>();
            var secondViewModel = container.Resolve <SecondViewModel>();

            var secondViewModelPageBeforePush          = secondViewModel.CurrentPage;
            var secondViewModelPreviousModelBeforePush = secondViewModel.PreviousModel;

            Assert.IsNull(secondViewModelPageBeforePush);
            Assert.IsNull(secondViewModelPreviousModelBeforePush);
            Assert.IsNull(secondViewModel.SecondStringProperty);

            await firstViewModel.Push <SecondPage>(stringValue);

            var secondViewModelPageAfterPush          = secondViewModel.CurrentPage;
            var secondViewModelPreviousModelAfterPush = secondViewModel.PreviousModel;

            Assert.IsNotNull(secondViewModelPageAfterPush);
            Assert.IsNotNull(secondViewModelPreviousModelAfterPush);
            Assert.AreEqual(secondViewModelPageAfterPush.GetType(), typeof(SecondPage));
            Assert.AreEqual(secondViewModelPreviousModelAfterPush.GetType(), typeof(FirstViewModel));
            Assert.AreEqual(firstViewModel, secondViewModel.PreviousModel);
            Assert.IsNotNull(secondViewModel.SecondStringProperty);
            Assert.AreEqual(stringValue, secondViewModel.SecondStringProperty);
        }
Exemplo n.º 7
0
        public void DryIoc()
        {
            var container = new DryIoc.Container();

            foreach (var type in _types)
            {
                container.Register(type, type);
            }
            int length = 0;

            if (Scenario == ResolveScenario.ResolveOne)
            {
                length = 1;
            }
            else if (Scenario == ResolveScenario.ResolveHalf)
            {
                length = _types.Length / 2;
            }
            else if (Scenario == ResolveScenario.ResolveAll)
            {
                length = _types.Length;
            }

            for (var i = 0; i < length; i++)
            {
                container.Resolve(_types[i]);
            }

            container.Dispose();
        }
Exemplo n.º 8
0
        public override TestResult DoTest(ITestCase testCase, int testCasesNumber, bool singleton)
        {
            var result = new TestResult { Singleton = singleton, TestCasesNumber = testCasesNumber };
            var sw = new Stopwatch();

            var c = new Container();
            if (singleton)
            {
                sw.Start();
                c = (Container)testCase.SingletonRegister(c);
                sw.Stop();
            }
            else
            {
                sw.Start();
                c = (Container)testCase.TransientRegister(c);
                sw.Stop();
            }
            result.RegisterTime = sw.ElapsedMilliseconds;

            sw.Reset();
            result.ResolveTime = DoResolve(sw, testCase, c, testCasesNumber, singleton);

            c.Dispose();

            return result;
        }
Exemplo n.º 9
0
            public DryIocContainerBuilder(
                IEnumerable <Assembly> pluginAssemblies,
                IEnumerable <string> pluginPaths,
                bool dslAspects = false)
            {
                this.DslAspects = dslAspects;
                var container = new DryIoc.Container(rules => rules.With(FactoryMethod.ConstructorWithResolvableArguments)).OpenScopeWithoutContext();

                Proxy = new CastleDynamicProxyProvider();
                this.RegisterSingleton <IMixinProvider>(Proxy);
                this.RegisterSingleton <IDynamicProxyProvider>(Proxy);
                var aopRepository = new AspectRepository(Proxy);

                this.RegisterSingleton <IAspectRegistrator>(aopRepository);
                this.RegisterSingleton <IAspectComposer>(aopRepository);
                this.RegisterSingleton <IInterceptorRegistrator>(aopRepository);
                Factory = new DryIocObjectFactory(container, aopRepository);
                this.RegisterSingleton <IObjectFactory>(Factory);
                this.RegisterSingleton <IServiceProvider>(Factory);
                Plugins = new PluginsConfiguration
                {
                    Directories = (pluginPaths ?? new string[0]).ToList(),
                    Assemblies  = (pluginAssemblies ?? new Assembly[0]).ToList()
                };
                this.RegisterSingleton(Plugins);
                this.RegisterType <SystemInitialization>();
                this.RegisterType(typeof(PluginRepository <>), InstanceScope.Singleton, true, typeof(IPluginRepository <>));
                var types = AssemblyScanner.GetAllTypes();

                this.RegisterSingleton <IExtensibilityProvider>(new DryIocMefProvider(Plugins, Proxy, container));
                DryIocObjectFactory.RegisterToContainer(container, this);
            }
Exemplo n.º 10
0
        public static Container Setup()
        {
            var container = new Container();

              RegisterConfigurations(container);

              return container;
        }
Exemplo n.º 11
0
 private static void SetupViewCommands(Container container)
 {
     container.Register<NameInputViewCommand>();
     container.Register<NameAndScoreInputViewCommand>();
     container.Register<DifficultyManagementViewCommand>();
     container.Register<NameAndLevelInputViewCommand>();
     container.Register<LogEntryInputViewCommand>();
 }
Exemplo n.º 12
0
 /// <summary>Adds all modules regs to container as final point.</summary>
 static void RegisterModules(DryIoc.Container container)
 {
     CommonModule.Register(container);
     DesktopCommonModule.Register(container);
     ServerModule.Register(container);
     FileSystemModule.Register(container);
     UIModule.Register(container);
 }
Exemplo n.º 13
0
        /// <summary>Shared through all session, but inner cmp to app scope initialization.</summary>
        static void RegisterSessionSingletons(DryIoc.Container container)
        {
            var tray = (TaskbarIcon)Application.Current.Resources["SysTray"];

            container.UseInstance(tray);
            container.UseInstance(new AppInfo(typeof(App).Assembly));
            container.UseInstance(TaskScheduler.FromCurrentSynchronizationContext()); // UI Tasks Scheduler
        }
Exemplo n.º 14
0
        public void RegisterDependencies(Container container)
        {
            //http context
            container.RegisterInstance<HttpContextBase>(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new SingletonReuse());

            //cache provider
            container.Register<ICacheProvider, HttpCacheProvider>(reuse: Reuse.Singleton);

            // settings register for access across app
            container.Register<IDatabaseSettings>(made: Made.Of(() => new DatabaseSettings()), reuse: Reuse.Singleton);

            //data provider : TODO: Use settings to determine the support for other providers
            container.Register<IDatabaseProvider>(made: Made.Of(() => new SqlServerDatabaseProvider()), reuse: Reuse.Singleton);

            //database context
            container.Register<IDatabaseContext>(made: Made.Of(() => DatabaseContextManager.GetDatabaseContext()), reuse: Reuse.Singleton);

            //and respositories
            container.Register(typeof(IDataRepository<>), typeof(EntityRepository<>));

            var asm = AssemblyLoader.LoadBinDirectoryAssemblies();

            //services
            //to register services, we need to get all types from services assembly and register each of them;
            var serviceAssembly = asm.First(x => x.FullName.Contains("mobSocial.Services"));
            var serviceTypes = serviceAssembly.GetTypes().
                Where(type => type.IsPublic && // get public types
                              !type.IsAbstract && // which are not interfaces nor abstract
                              type.GetInterfaces().Length != 0);// which implementing some interface(s)

            container.RegisterMany(serviceTypes, reuse: Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Replace);

            //we need a trasient reporter service rather than singleton
            container.Register<IVerboseReporterService, VerboseReporterService>(reuse: Reuse.InResolutionScope, ifAlreadyRegistered:IfAlreadyRegistered.Replace);

            //settings
            var allSettingTypes = TypeFinder.ClassesOfType<ISettingGroup>();
            foreach (var settingType in allSettingTypes)
            {
                var type = settingType;
                container.RegisterDelegate(type, resolver =>
                {
                    var instance = (ISettingGroup) Activator.CreateInstance(type);
                    resolver.Resolve<ISettingService>().LoadSettings(instance);
                    return instance;
                }, reuse: Reuse.Singleton);

            }
            //and ofcourse the page generator
            container.Register<IPageGenerator, PageGenerator>(reuse: Reuse.Singleton);

            //event publishers and consumers
            container.Register<IEventPublisherService, EventPublisherService>(reuse: Reuse.Singleton);
            //all consumers which are not interfaces
            container.RegisterMany(new[] {typeof(IEventConsumer<>)}, serviceTypeCondition: type => !type.IsInterface);
        }
        public static IContainer BootstrapIoCContainer()
        {
            var container = new Container();

            container.Register<IEVEBootstrap, EVEBootstrap>();
            container.Register<IExecuteEVEActions, EveActionExecutor>();
            container.Register<IQuickAutopilotLogic, QuickAutopilotLogic>();

            return container;
        }
Exemplo n.º 16
0
        public DryIocObjectFactory(
            Container lifetimeScope,
            IAspectComposer aspects)
        {
            Contract.Requires(lifetimeScope != null);
            Contract.Requires(aspects != null);

            CurrentScope = lifetimeScope;
            this.Aspects = aspects;
        }
Exemplo n.º 17
0
        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;
        }
Exemplo n.º 18
0
        public void container_can_resolve_personlistviewmodel()
        {
            var ass = Assembly.GetAssembly(typeof(PersonListViewModel));
            var container = new Container();
            container.Register(typeof (IRepository<Person>), typeof (TestPersonRepository));

            container = container.RegisterViewModels(ass);

            var personListVm = container.Resolve<IListViewModel<Person>>();
            Assert.IsNotNull(personListVm, "PersonListViewModel could not be resolved");
        }
Exemplo n.º 19
0
 private static void RegisterServices(Container container)
 {
     container.Register<ICountryService, CountryService>();
     container.Register<IAreaService, AreaService>();
     container.Register<ISummitGroupService, SummitGroupService>();
     container.Register<ISummitService, SummitService>();
     container.Register<IRouteService, RouteService>();
     container.Register<IVariationService, VariationService>();
     container.Register<ILogEntryService, LogEntryService>();
     container.Register<IDifficultyLevelScaleService, DifficultyLevelScaleService>();
     container.Register<IDifficultyLevelService, DifficultyLevelService>();
 }
Exemplo n.º 20
0
 private static void RegisterDaos(Container container)
 {
     container.Register<ICountryDao, CountryDao>();
     container.Register<IAreaDao, AreaDao>();
     container.Register<ISummitGroupDao, SummitGroupDao>();
     container.Register<ISummitDao, SummitDao>();
     container.Register<IRoutesDao, RouteDao>();
     container.Register<IDifficultyLevelScaleDao, DifficultyLevelScaleDao>();
     container.Register<IDifficultyLevelDao, DifficultyLevelDao>();
     container.Register<IVariationDao, VariationDao>();
     container.Register<ILogEntryDao, LogEntryDao>();
 }
Exemplo n.º 21
0
        internal static void Register(DryIoc.Container container)
        {
            container.Register <AppTrayViewModel>(Reuse.Singleton);
            container.Register <AppTrayView>(Reuse.Singleton);
            container.Register <ITrayTooltipNotifier, TrayTooltipNotifier>(Reuse.Singleton);
            //#if DEBUG
            //            container.RegisterInitializer<object>((service, resolver) =>
            //                Trace.TraceWarning($"RESOLVED obj: {service.GetType()}"));
            //#endif

            // container.Register<ICoreDataConnection, CoreDataConnection>(Reuse.Singleton);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Constructs the service provider around the given context.
        /// </summary>
        /// <param name="context">The system context in which this service provider
        /// will be constructed around.</param>
        public SystemServiceProvider(ISystemContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            SystemContext = context;

            container = new DryIoc.Container();
            container.RegisterInstance<ISystemContext>(context);

            resolveContexts = new List<IServiceResolveContext>();
        }
        public static DryIoc.IContainer PrepareDryIoc()
        {
            var container = new Container();

            container.Register <Parameter1>(Reuse.Transient);
            container.Register <Parameter2>(Reuse.Singleton);
            container.Register <Parameter3>(Reuse.Scoped);

            container.Register <ScopedBlah>(Reuse.Scoped);

            return(container);
        }
Exemplo n.º 24
0
        /// <summary>Builds container and invokes specified 'intializer' against ready container.</summary>
        internal Container() // (Func<Container, T> with)
        {
            _container = new DryIoc.Container();

            RegisterAppScopeServices(_container);
            RegisterSessionSingletons(_container);
            RegisterModules(_container);
            //var root = with(_container);
            //var root = container.Resolve<T>();
            //_container.WithNoMoreRegistrationAllowed();
            //return (container, root);
        }
Exemplo n.º 25
0
        public override void Prepare()
        {
            this.container = new Container();

            this.RegisterDummies();
            this.RegisterStandard();
            this.RegisterComplex();
            this.RegisterPropertyInjection();
            this.RegisterOpenGeneric();
            this.RegisterConditional();
            this.RegisterMultiple();
        }
Exemplo n.º 26
0
        private static IMediator BuildMediator()
        {
            var container = new Container();

            container.RegisterDelegate<SingleInstanceFactory>(r => serviceType => r.Resolve(serviceType));
            container.RegisterDelegate<MultiInstanceFactory>(r => serviceType => r.ResolveMany(serviceType));
            container.RegisterInstance(Console.Out);

            container.RegisterMany(new[] { typeof(IMediator).GetAssembly(), typeof(Ping).GetAssembly() }, type => type.GetTypeInfo().IsInterface);

            return container.Resolve<IMediator>();
        }
Exemplo n.º 27
0
 private static void SetupViewModels(Container container)
 {
     container.Register<IMainViewModel, MainViewModel>();
     container.Register<INameInputViewModel, NameInputViewModel>();
     container.Register<IDifficultyLevelScaleManagementViewModel, DifficultyLevelScaleManagementViewModel>();
     container.Register<IDifficultyLevelManagementViewModel, DifficultyLevelManagementViewModel>();
     container.Register<INameAndScoreInputViewModel, NameAndScoreInputViewModel>();
     container.Register<IDifficultyManagementViewModel, DifficultyManagementViewModel>();
     container.Register<INameAndLevelInputViewModel, NameAndLevelInputViewModel>();
     container.Register<ILogEntryInputViewModel, LogEntryInputViewModel>();
     container.Register<ILogItemViewModel, LogItemViewModel>();
     container.Register<IVariationItemViewModel, VariationItemViewModel>();
 }
Exemplo n.º 28
0
 private InversionOfControlContainer()
 {
     container = new Container(rules => rules.WithoutThrowOnRegisteringDisposableTransient());
     container.Register<INewsService, NewsService>(Reuse.Singleton);
     container.Register<INewsDao, NewsDao>(Reuse.Singleton);
     container.Register<IProvider, Provider>(Reuse.Singleton);
     container.Register<IPersonDao, PersonDao>(Reuse.Singleton);
     container.Register<IPersonService, PersonService>(Reuse.Singleton);
     container.Register<IUserSevice, UserService>(Reuse.Singleton);
     container.Register<IUserDao, UserDao>(Reuse.Singleton);
     container.Register<ICommentService, CommentService>(Reuse.Singleton);
     container.Register<ICommentDao, CommentDao>(Reuse.Singleton);
 }
Exemplo n.º 29
0
        /// <summary>
        ///     Initialisiert den Bootloader
        /// </summary>
        /// <param name="container"></param>
        /// <returns></returns>
        public static Container Init(Container container)
        {

            GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "extra");
            client.Connect();

            container.RegisterInstance(client);

            RegisterDaos(container);
            RegisterServices(container);

            return container;
        }
Exemplo n.º 30
0
        public void SetUp()
        {
            Xamarin.Forms.Mocks.MockForms.Init();

            this._container = new Container();
            this._app       = new Application();

            ZeroApp
            .On(this._app)
            .WithContainer(DryIocZeroContainer.Build(this._container))
            .RegisterShell(() => new FirstShell())
            .Start();
        }
Exemplo n.º 31
0
        public void TransientRegister_Success()
        {
            ITestCase testCase = new TestCaseA();

            var c = new Container();
            c = (Container)testCase.TransientRegister(c);

            var obj1 = c.Resolve<ITestA>();
            var obj2 = c.Resolve<ITestA>();

            Assert.AreNotEqual(obj1, obj2);
            Helper.Check(obj1, false);
            Helper.Check(obj2, false);
        }
Exemplo n.º 32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddApplicationInsightsTelemetry(Configuration);
            services.AddMvc();

            // DryIOC
            // http://stackoverflow.com/questions/36179819/dryioc-asp-net-5-web-api
            var container = new DryIoc.Container().WithDependencyInjectionAdapter(services);

            container.Register <ICustomerRepository, CustomerRepository>(Reuse.Singleton);
            var serviceProvider = container.Resolve <IServiceProvider>();

            return(serviceProvider);
        }
Exemplo n.º 33
0
        public void SingletonRegister_Success()
        {
            ITestCase testCase = new TestCaseA();

            var c = new Container();
            c = (Container)testCase.SingletonRegister(c);

            var obj1 = c.Resolve<ITestA>();
            var obj2 = c.Resolve<ITestA>();

            Assert.AreEqual(obj1, obj2);
            Helper.Check(obj1, true);
            Helper.Check(obj2, true);
        }
Exemplo n.º 34
0
        public IGame BuildGame()
        {
            var container = new Container();

            new AlphaCivPackage().Load(container);

            new FixedCities().SetUpCities(() => new DryIocCityBuilder(container));
            new ThreeUnitsWithoutActions().SetUpUnits(() => new DryIocUnitBuilder(container));

            var game = container.Resolve<IGame>();
            game.ContainerName = "DryIoc/AlphaCiv";

            return game;
        }
Exemplo n.º 35
0
        void Configure(IAppBuilder app_)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            var di = new DryIoc.Container();

            di.RegisterInstance <IBackStore>(new BackStore(), Reuse.Singleton);

            di.WithWebApi(config);
            app_.UseDryIocOwinMiddleware(di);

            app_.UseWebApi(config);
        }
Exemplo n.º 36
0
        private static IContainer InitializeContainer()
        {
            var rules = Rules.Default
                        .WithAutoConcreteTypeResolution()
                        .With(Made.Of(FactoryMethod.ConstructorWithResolvableArguments))
                        .WithoutThrowOnRegisteringDisposableTransient()
                        .WithFuncAndLazyWithoutRegistration()
#if __IOS__
                        .WithoutFastExpressionCompiler()
#endif
                        .WithDefaultIfAlreadyRegistered(IfAlreadyRegistered.Replace);
            var container = new Container(rules);

            RegisterRequiredServices(container);
            return(container);
        }
Exemplo n.º 37
0
        protected void Application_Start(object sender, EventArgs e)
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);

            IContainer container = new Container();

            container.Register<IProductRepository, FakeProductRepository>(WebReuse.InRequest);

            container.RegisterDelegate<ILogger>(
                resolver => new Logger(s => Debug.WriteLine(s)),
                Reuse.Singleton);

            container.Register<ProductsController>(WebReuse.InRequest);

            container.WithWebApi(GlobalConfiguration.Configuration);
        }
Exemplo n.º 38
0
        internal static void Register(DryIoc.Container container)
        {
            Type getImplType(Request r) => r.Parent.ImplementationType;

            // https://bitbucket.org/dadhi/dryioc/wiki/ExamplesContextBasedResolution
            container.Register(
                made: Made.Of(() => LogManager.GetCurrentClassLogger(Arg.Index <Type>(0)), getImplType),
                setup: Setup.With(condition: req => req.Parent.ImplementationType != null),
                reuse: Reuse.Transient);

            container.UseInstance(new EnvInfo());

            container.Register <ISettingsService, SettingsService>(Reuse.Singleton);
            container.Register(typeof(IShell <>), typeof(CommandPromptShell), Reuse.Singleton); // reg open gen https://bitbucket.org/dadhi/dryioc/wiki/OpenGenerics
            container.Register <IWebBrowser, WebBrowser>(Reuse.Singleton);
        }
Exemplo n.º 39
0
        public void RegisterDependencies(Container container)
        {
            container.Register<IClientService, ClientService>();
            container.Register<IAppTokenService, AppTokenService>();

            container.RegisterDelegate<IDataRepository<OAuthClient>>(
                resolver => new EntityRepository<OAuthClient>(DatabaseContextManager.GetDatabaseContext<OAuthDbContext>()),
                ifAlreadyRegistered: IfAlreadyRegistered.Replace);

            container.RegisterDelegate<IDataRepository<AppToken>>(
               resolver => new EntityRepository<AppToken>(DatabaseContextManager.GetDatabaseContext<OAuthDbContext>()),
               ifAlreadyRegistered: IfAlreadyRegistered.Replace);

            //override authentication service
            container.Register<IAuthenticationService, OAuthAuthenticationService>(
                ifAlreadyRegistered: IfAlreadyRegistered.Replace, reuse: Reuse.Singleton);
        }
Exemplo n.º 40
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            WebApiConfig.Register(config);
            var container = new DryIoc.Container();



            //  ReplaceControllersIOCLifeCircle(config, container);

            //dry
            container.Register <ILixo, Lixo>(Reuse.Transient, ifAlreadyRegistered: IfAlreadyRegistered.Replace);


            var modelBuilder = new ODataConventionModelBuilder(config);

            modelBuilder.EnableLowerCamelCase();
            config.EnableCaseInsensitive(true);

            modelBuilder.EntitySet <Person>("People");


            var server = new HttpServer(config);

            config.MapODataServiceRoute(
                ODataConstants.RouteName,
                ODataConstants.RoutePrefix,
                modelBuilder.GetEdmModel(),
                new DefaultODataBatchHandler(server)
                );


            //app.UseDryIocOwinMiddleware(container);

            app
            .UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll)
            .UseWebApi(server)
            .UseDryIocWithTransientControllers(container, config)


            ;
        }
Exemplo n.º 41
0
        internal static DryIoc.IContainer Compose()
        {
            var c = new DryIoc.Container();

            c.Register <DirectoriesViewModel>(Reuse.Singleton);
            c.Register <SyncsViewModel>(Reuse.Singleton);
            c.Register <MainViewModel>(Reuse.Singleton);

            c.Register <IBusyStack, BusyStack>(Reuse.Transient);

            c.UseInstance(ScarletCommandBuilder.Default);
            c.UseInstance(ScarletCommandManager.Default);
            c.UseInstance(ScarletDispatcher.Default);
            c.UseInstance(ScarletExitService.Default);
            c.UseInstance(ScarletMessenger.Default);
            c.UseInstance(ScarletWeakEventManager.Default);

            return(c);
        }
Exemplo n.º 42
0
        static void Main(string[] args)
        {
            var container = new DryIoc.Container();

            container.Register <IMySuperService, MySuperServiceImpl>(Reuse.Transient);
            container.Register <IMyWorker, MyWorkerImpl>();



            var worker = container.Resolve <IMyWorker>();

            worker.Work();

            var worker2 = container.Resolve <IMyWorker>();

            worker2.Work();

            System.Console.ReadLine();
        }
Exemplo n.º 43
0
        static void Main(string[] args)
        {
            Container container = new Container();
            container.Register<ICalculo, Soma>();
            container.Register<ICalculo, Subtracao>();
            container.Register<Calculadora>(Reuse.Singleton);

            Calculadora calculadora = container.Resolve<Calculadora>();
            calculadora.EfetuarCalculos(500, 200);

            IEnumerable<ICalculo> calculos = container.Resolve<IEnumerable<ICalculo>>();
            foreach (var calculo in calculos)
            {
                var result = calculo.Calcular(100, 50);
                Console.WriteLine($"Resultado: {result}");
            }

            Console.Read();
        }
Exemplo n.º 44
0
        public void Configuration(IAppBuilder app)
        {
            var webApiConfig = new HttpConfiguration();
            var hubConfig = new HubConfiguration
            {
                EnableJSONP = true,
                EnableJavaScriptProxies = true
            };

            webApiConfig.MapHttpAttributeRoutes();
            webApiConfig.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            webApiConfig.EnableCors(
                new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE, PATCH")
            );

            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                FileSystem = new WebPhysicalFileSystem(".\\wwwroot")
            };

            var container = new Container()
                .WithWebApi(webApiConfig)
                .WithSignalR(Assembly.GetExecutingAssembly());

            container.Register<ITest, Test>();

            app.Use(new Func<AppFunc, AppFunc>(next => env => Invoke(next, env)))
                .UseErrorPage(ErrorPageOptions.ShowAll)
                .UseCors(CorsOptions.AllowAll)
                .Use(typeof(OwinMiddleWareQueryStringExtractor))
                .UseOAuthAuthorizationServer(new OAuthOptions())
                .UseJwtBearerAuthentication(new JwtOptions())
                .UseAngularServer("/", "/index.html")
                .UseFileServer(options)
                .UseWebApi(webApiConfig)
                .MapSignalR(hubConfig);
        }
Exemplo n.º 45
0
        public static IContainer BuildContainer()
        {
            var container = new DryIoc.Container();


            container.Register <SampleDbContext>(reuse: Reuse.Scoped);
            container.Register <TraceInterceptor>(reuse: Reuse.Transient);
            container.Register <TraceInterceptorAsync>(reuse: Reuse.Transient);
            container.RegisterMany(
                typeof(ICustomerFindService).Assembly.GetTypes().Where(x => x.IsDependencyComponent()),
                serviceTypeCondition: t => t.IsComponentInterface(),
                reuse: Reuse.Scoped,
                ifAlreadyRegistered: IfAlreadyRegistered.Replace

                );


            container.Intercept <TraceInterceptor>(t => t.IsComponentInterface());
            return(container);
        }
Exemplo n.º 46
0
        internal static IBus Build(Config configuration)
        {
            var logger = configuration.Logger;
            logger.Debug("Constructing bus...");

            _container = _container ?? new Container();

            _container.Register(configuration.Logger.GetType(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.Register(configuration.Serializer.GetType(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.Register(configuration.Compressor.GetType(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.Register(configuration.Transport.GetType(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            _container.RegisterMany(configuration.CommandPipeline.GetCommandHandlerTypes(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.CommandPipeline.GetCommandTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.CommandPipeline.GetPreHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.CommandPipeline.GetPostHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.CommandPipeline.GetErrorHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            _container.RegisterMany(configuration.EventPipeline.GetCompetingEventHandlerTypes(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.EventPipeline.GetMulticastEventHandlerTypes(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.EventPipeline.GetEventTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.EventPipeline.GetPreHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.EventPipeline.GetPostHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.EventPipeline.GetErrorHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            _container.RegisterMany(configuration.RequestResponsePipeline.GetRequestHandlerTypes(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetMulticastRequestHandlerTypes(), Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetRequestTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetResponseTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetPreHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetPostHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.RegisterMany(configuration.RequestResponsePipeline.GetErrorHookTypes(), ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            _container.Register<IPipeline, CommandPipeline>(Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.Register<IPipeline, EventPipeline>(Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);
            _container.Register<IPipeline, RequestResponsePipeline>(Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            _container.Register<IBus, Bus>(Reuse.Singleton, ifAlreadyRegistered: IfAlreadyRegistered.Keep);

            return _container.Resolve<IBus>();
        }
Exemplo n.º 47
0
        public Locator()
        {
            Container = new Container();
            Container.Register<IBitmapFactory, PclBitmapFactory>(Reuse.Singleton);
            Container.Register<IAppSettingsHelper, AppSettingsHelper>(Reuse.Singleton);
            Container.Register<IDispatcherHelper, DispatcherHelper>(Reuse.Singleton);
            Container.Register<INotificationManager, NotificationManager>(Reuse.Singleton);
            Container.Register<ICredentialHelper, CredentialHelper>(Reuse.Singleton);

            var factory = new AudioticaFactory(DispatcherHelper, AppSettingsHelper, BitmapFactory);

            Container.Register<IScrobblerService, ScrobblerService>(Reuse.Singleton);
            Container.Register<SpotifyWebApi>(Reuse.Singleton);
            Container.Register<ISpotifyService, SpotifyService>(Reuse.Singleton);

            Container.RegisterDelegate(r => factory.CreateCollectionSqlService(10), Reuse.Singleton);
            Container.RegisterDelegate(r => factory.CreatePlayerSqlService(4), Reuse.Singleton, named: "BackgroundSql");
            Container.RegisterDelegate(r => factory.CreateCollectionService(SqlService, BgSqlService), Reuse.Singleton);

            Container.Register<Mp3MatchEngine>(Reuse.Singleton);
        }
Exemplo n.º 48
0
        public static void Main(string[] args)
        {
            var dryIoc = new DryIoc.Container();

            ContainerRegistrar.Register((x, y) => dryIoc.Register(x, y));
            dryIoc.Register <ILogger, ConsoleLogger>();

            var unity = new UnityContainer();

            ContainerRegistrar.Register((x, y) => unity.RegisterType(x, y));
            unity.RegisterType <ILogger, ConsoleLogger>();

            var structureMap = new StructureMap.Container(c => {
                ContainerRegistrar.Register((x, y) => c.For(x).Use(y));
                c.For <ILogger>().Use <ConsoleLogger>();
            });

            var autofac = new Autofac.ContainerBuilder();

            ContainerRegistrar.Register((x, y) => autofac.RegisterType(x).As(y));
            autofac.RegisterType <ILogger>().As <ConsoleLogger>();
        }
Exemplo n.º 49
0
        public void Test_ViewModels_ShellService_And_MessagingCenter_Are_Registered_On_Startup()
        {
            var container = new Container();
            var app       = new Application();

            ZeroApp
            .On(app)
            .WithContainer(DryIocZeroContainer.Build(container))
            .RegisterShell(() => new FirstShell())
            .Start();

            var firstViewModel  = container.Resolve <FirstViewModel>();
            var secondViewModel = container.Resolve <SecondViewModel>();

            var shellService    = container.Resolve <IShellService>();
            var messagingCenter = container.Resolve <IMessagingCenter>();

            Assert.NotNull(firstViewModel);
            Assert.NotNull(secondViewModel);
            Assert.NotNull(shellService);
            Assert.NotNull(messagingCenter);
        }
Exemplo n.º 50
0
        public SimpleObjectBenchmarks()
        {
            var serviceContainer = new ServiceContainer();

            serviceContainer.Transients.AddType <IUserService, UserService1>();
            serviceContainer.Transients.AddType <IUserService, UserService2>();
            serviceContainer.Transients.AddType <IUserService, UserService>();
            serviceContainer.Transients.AddType(typeof(IRepository <>), typeof(Repository <>));
            serviceResolver = serviceContainer.Build();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddTransient <IUserService, UserService1>();
            serviceCollection.AddTransient <IUserService, UserService2>();
            serviceCollection.AddTransient <IUserService, UserService>();
            serviceCollection.AddTransient(typeof(IRepository <>), typeof(Repository <>));
            serviceProvider = serviceCollection.BuildServiceProvider();

            var containerBuilder = new ContainerBuilder();

            containerBuilder.RegisterType <UserService1>().As <IUserService>().InstancePerDependency();
            containerBuilder.RegisterType <UserService2>().As <IUserService>().InstancePerDependency();
            containerBuilder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>));
            containerBuilder.RegisterType <UserService>().As <IUserService>().InstancePerDependency();
            autofacContainer = containerBuilder.Build();

            zkWebContainer = new ZKWebContainer();
            zkWebContainer.Register <IUserService, UserService1>(ReuseType.Transient, null);
            zkWebContainer.Register <IUserService, UserService2>(ReuseType.Transient, null);
            zkWebContainer.Register <IUserService, UserService>(ReuseType.Transient, null);
            zkWebContainer.Register(typeof(IRepository <>), typeof(Repository <>), ReuseType.Transient, null);

            dryIocContainer = new DryIocContainer();
            dryIocContainer.Register <IUserService, UserService1>();
            dryIocContainer.Register <IUserService, UserService2>();
            dryIocContainer.Register <IUserService, UserService>();
            dryIocContainer.Register(typeof(IRepository <>), typeof(Repository <>));
        }
        public static void RegisterIoC(HttpConfiguration config)
        {
            var appCfg = new AppConfiguration();
            var di     = new DryIoc.Container().WithWebApi(config);

            var creds =
                new GraphCredentials
            {
                ClientId = appCfg.ClientId, // "5c642f80-ae79-4d3a-a753-5498eeb2e7d0",
                Key      = appCfg.Key,      //"6WxvoAUri6JXdEDIdTISz/SfCRZa7NUZCL7nAl4lcoM=",
                Tenant   = appCfg.TenantId  //"e58cae89-8f91-4f69-8cce-51abf1d13b44"
            };

            di.Register <IGroupRepository, GroupRepository>(setup: Setup.With(trackDisposableTransient: true));
            di.Register <IUserGroupManager, UserGroupManager>(Made.Of(() =>
                                                                      new UserGroupManager(creds, Arg.Of <IGroupRepository>())));
            di.Register <IAdminGroupManager, AdminGroupManager>(Made.Of(() =>
                                                                        new AdminGroupManager(creds, Arg.Of <IGroupRepository>())));

            var errors = di.VerifyResolutions();

            Debug.Assert(errors.Length == 0);
        }
Exemplo n.º 52
0
        public async Task Pop_And_ReversePrepare_Model(string stringValue)
        {
            var container = new Container();
            var app       = new Application();

            ZeroApp
            .On(app)
            .WithContainer(DryIocZeroContainer.Build(container))
            .RegisterShell(() => new FirstShell())
            .Start();

            var firstViewModel  = container.Resolve <FirstViewModel>();
            var secondViewModel = container.Resolve <SecondViewModel>();

            Assert.AreEqual(firstViewModel.CurrentPage.GetType(), typeof(FirstPage));
            Assert.IsNull(secondViewModel.CurrentPage);

            Assert.AreEqual(firstViewModel.CurrentPage.Navigation.NavigationStack.Count, 1);

            await firstViewModel.Push <SecondPage>();

            Assert.AreEqual(firstViewModel.CurrentPage.Navigation.NavigationStack.Count, 2);

            Assert.AreEqual(firstViewModel.CurrentPage.GetType(), typeof(FirstPage));
            Assert.AreEqual(secondViewModel.CurrentPage.GetType(), typeof(SecondPage));

            await secondViewModel.Pop(stringValue);

            Assert.AreEqual(firstViewModel.CurrentPage.Navigation.NavigationStack.Count, 1);

            Assert.AreEqual(firstViewModel.CurrentPage.GetType(), typeof(FirstPage));
            Assert.AreEqual(secondViewModel.CurrentPage.GetType(), typeof(SecondPage));

            Assert.NotNull(firstViewModel.FirstStringProperty);
            Assert.AreEqual(firstViewModel.FirstStringProperty, stringValue);
        }
Exemplo n.º 53
0
 public DryIocContainer()
 {
     _Container = new DryIoc.Container(rules => rules.NotNull().WithAutoConcreteTypeResolution());
 }
Exemplo n.º 54
0
 public override void Dispose()
 {
     // Allow the container and everything it references to be disposed.
     this.container.Dispose();
     this.container = null;
 }
Exemplo n.º 55
0
 public HandlerRegistry(Container container) => _container = container;
Exemplo n.º 56
0
        private void BuildScopeIfRequired()
        {
            if (!ShouldBuildScope)
                return;
            lock (sync)
            {
                if (!ShouldBuildScope)
                    return;
                CurrentScope = CurrentScope.OpenScope();
                RegisterNew();

                FactoryBuilders.Clear();
                ShouldBuildScope = false;

                MyScopes.Push(CurrentScope);
            }
        }
Exemplo n.º 57
0
 /// <summary>App scope initialization services regs. The most outer block, thus creating container builder.</summary>
 static void RegisterAppScopeServices(DryIoc.Container container)
 {
     // todo: implement and use with split into diff scopes: 1) init doesn't need all the stuff, even UI so will be quick
 }
Exemplo n.º 58
0
        static public void Main(string[] args)
        {
            var _benchmark = new Benchmark(() => new Action(() => new Calculator()));

            _benchmark.Add("SimpleInjector", () =>
            {
                var _container = new SimpleInjector.Container();
                _container.Register <ICalculator, Calculator>(SimpleInjector.Lifestyle.Transient);
                return(() => _container.GetInstance <ICalculator>());
            });
            //TODO : change to test new Puresharp DI recast
            _benchmark.Add("Puresharp", () =>
            {
                var _container = new Puresharp.Composition.Container();
                _container.Add <ICalculator>(() => new Calculator(), Puresharp.Composition.Lifetime.Volatile);
                return(() => _container.Enumerable <ICalculator>());
            });
            //TODO : change to test MEF2
            _benchmark.Add("MEF", () =>
            {
                var _container = new System.Composition.Hosting.ContainerConfiguration().WithAssembly(typeof(ICalculator).Assembly).CreateContainer();
                return(() => _container.GetExport <ICalculator>());
            });
            _benchmark.Add("Castle Windsor", () =>
            {
                var _container = new WindsorContainer();
                _container.Register(Castle.MicroKernel.Registration.Component.For <ICalculator>().ImplementedBy <Calculator>());
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Unity", () =>
            {
                var _container = new UnityContainer();
                _container.RegisterType <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("StuctureMap", () =>
            {
                var _container = new StructureMap.Container(_Builder => _Builder.For <ICalculator>().Use <Calculator>());
                return(() => _container.GetInstance <ICalculator>());
            });
            _benchmark.Add("DryIoc", () =>
            {
                var _container = new DryIoc.Container();
                _container.Register <ICalculator, Calculator>();
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Autofac", () =>
            {
                var _builder = new Autofac.ContainerBuilder();
                _builder.RegisterType <Calculator>().As <ICalculator>();
                var _container = _builder.Build(Autofac.Builder.ContainerBuildOptions.None);
                return(() => _container.Resolve <ICalculator>());
            });
            _benchmark.Add("Ninject", () =>
            {
                var _container = new Ninject.StandardKernel();
                _container.Bind <ICalculator>().To <Calculator>();
                return(() => _container.Get <ICalculator>());
            });
            _benchmark.Add("Abioc", () =>
            {
                var _setup = new Abioc.Registration.RegistrationSetup();
                _setup.Register <ICalculator, Calculator>();
                var _container = Abioc.ContainerConstruction.Construct(_setup, typeof(ICalculator).Assembly);
                return(() => _container.GetService <ICalculator>());
            });
            _benchmark.Add("Grace", () =>
            {
                var _container = new Grace.DependencyInjection.DependencyInjectionContainer();
                _container.Configure(c => c.Export <Calculator>().As <ICalculator>());
                return(() => _container.Locate <ICalculator>());
            });
            _benchmark.Run(Console.WriteLine);
        }
Exemplo n.º 59
0
 public ActivatedContainer(Container container)
 {
     _container = container;
 }
Exemplo n.º 60
0
        private void Dispose(bool disposing)
        {
            if (disposing) {
                lock (this) {
                    container.Dispose();
                }
            }

            container = null;
        }