public void SetUp()
        {
            _container = new Container(x => x.For(typeof(IEventQueueFactory <>)).Use(typeof(DefaultEventQueueFactory <>)));
            var services = new StructureMapServiceLocator(_container);

            _factory = new EventQueueFactory(services);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            // Use the car without any service injection
            var car = new FamilyCar();

            car.Move();
            car.Stop();

            var host = car as IActivatorHost;

            if (host == null)
            {
                return;
            }

            // Configure the StructureMap container
            var registry = new Registry();

            registry.ForRequestedType <Engine>().
            TheDefaultIsConcreteType <RaceCarEngine>();

            var container = new Container(registry);
            var locator   = new StructureMapServiceLocator(container);
            var activator = new ContainerTypeActivator(locator);


            host.Activator = activator;

            // Use the car after the new operator call has been
            // replaced with the call to the SM container
            car.Move();
            car.Stop();

            return;
        }
Beispiel #3
0
        public void SetUp()
        {
            var container = new Container();
            var locator   = new StructureMapServiceLocator(container);

            finder = new ServiceEnabledObjectConverter(locator);
        }
Beispiel #4
0
        public static void RegisterDependencies()
        {
            Container = new Container(cfg =>
            {
                cfg.Scan(scan =>
                {
                    scan.AssembliesFromApplicationBaseDirectory(
                        assembly => assembly.FullName.EndsWith(".Tests") == false);
                    scan.LookForRegistries();

                    scan.AssemblyContainingType <ListProductQuery>();
                    scan.AssemblyContainingType <IMediator>();
                    scan.WithDefaultConventions();
                    scan.AddAllTypesOf(typeof(IRequestHandler <,>));

                    scan.ConnectImplementationsToTypesClosing(typeof(AbstractValidator <>));
                });

                cfg.For <TextWriter>().Use(Console.Out);

                cfg.For(typeof(IRequestHandler <,>)).DecorateAllWith(typeof(ValidatorHandler <,>));

                cfg.For <IDatabaseAdapter>().Use <SqLiteDatabaseAdapter>();
            });

            var serviceLocator         = new StructureMapServiceLocator(Container);
            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);

            Container.Configure(cfg => cfg.For <ServiceLocatorProvider>().Use(serviceLocatorProvider));

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(Container));
            Dependency.SetupContainer(Container);
        }
Beispiel #5
0
        public static IContainer BootstrapApplication(HttpConfiguration config)
        {
            var container = new Container(cfg => cfg.Scan(scanner =>
            {
                scanner.Assembly(typeof(Person).Assembly);
                scanner.Assembly(typeof(BaseController).Assembly);
                scanner.AssemblyContainingType<IMediator>();
                scanner.WithDefaultConventions();
                scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
                scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
                scanner.AddAllTypesOf(typeof(IPostRequestHandler<,>));
                scanner.AddAllTypesOf(typeof(IAsyncPostRequestHandler<,>));
                scanner.AddAllTypesOf(typeof(INotificationHandler<>));
                scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
                scanner.AddAllTypesOf<Profile>();
                scanner.AddAllTypesOf(typeof(IValidator<>));
                scanner.LookForRegistries();
            }));

            var serviceLocator = new StructureMapServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);

            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);
            container.Configure(cfg => cfg.For<ServiceLocatorProvider>().Use(serviceLocatorProvider));

            config.DependencyResolver = new StructureMapResolver(container);

            return container;
        }
Beispiel #6
0
        public static IContainer BootstrapApplication(HttpConfiguration config)
        {
            var container = new Container(cfg => cfg.Scan(scanner =>
            {
                scanner.Assembly(typeof(Person).Assembly);
                scanner.Assembly(typeof(BaseController).Assembly);
                scanner.AssemblyContainingType <IMediator>();
                scanner.WithDefaultConventions();
                scanner.AddAllTypesOf(typeof(IRequestHandler <,>));
                scanner.AddAllTypesOf(typeof(IAsyncRequestHandler <,>));
                scanner.AddAllTypesOf(typeof(IPostRequestHandler <,>));
                scanner.AddAllTypesOf(typeof(IAsyncPostRequestHandler <,>));
                scanner.AddAllTypesOf(typeof(INotificationHandler <>));
                scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler <>));
                scanner.AddAllTypesOf <Profile>();
                scanner.AddAllTypesOf(typeof(IValidator <>));
                scanner.LookForRegistries();
            }));

            var serviceLocator = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => serviceLocator);

            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);

            container.Configure(cfg => cfg.For <ServiceLocatorProvider>().Use(serviceLocatorProvider));

            config.DependencyResolver = new StructureMapResolver(container);

            return(container);
        }
Beispiel #7
0
        public static void RegisterDependencies()
        {
            Container = new Container(cfg =>
            {
                cfg.Scan(scan =>
                {
                    scan.AssembliesFromApplicationBaseDirectory(
                        assembly => assembly.FullName.EndsWith(".Tests") == false);
                    scan.LookForRegistries();

                    scan.AssemblyContainingType<ListProductQuery>();
                    scan.AssemblyContainingType<IMediator>();
                    scan.WithDefaultConventions();
                    scan.AddAllTypesOf(typeof (IRequestHandler<,>));

                    scan.ConnectImplementationsToTypesClosing(typeof (AbstractValidator<>));
                });

                cfg.For<TextWriter>().Use(Console.Out);

                cfg.For(typeof (IRequestHandler<,>)).DecorateAllWith(typeof (ValidatorHandler<,>));

                cfg.For<IDatabaseAdapter>().Use<SqLiteDatabaseAdapter>();
            });

            var serviceLocator = new StructureMapServiceLocator(Container);
            var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);

            Container.Configure(cfg => cfg.For<ServiceLocatorProvider>().Use(serviceLocatorProvider));

            DependencyResolver.SetResolver(new StructureMapDependencyResolver(Container));
            Dependency.SetupContainer(Container);
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            var registry = new Registry();

            registry.Scan(scanner =>
            {
                scanner.TheCallingAssembly();
                scanner.AssembliesFromApplicationBaseDirectory();

                scanner.LookForRegistries();

                scanner.RegisterConcreteTypesAgainstTheFirstInterface();

                scanner.WithDefaultConventions();
            });
            var container = new Container(registry);

            StructureMapServiceLocator.SetTheContainer(container);

            var cqrs = container.GetInstance <CqrsRuntime>();

            cqrs.SetServiceLocator();
            cqrs.Start();

            Console.WriteLine("Started");
            var line = Console.ReadLine();
        }
        private static void SetServiceLocator(IContainer container)
        {
            var serviceLocator = new StructureMapServiceLocator(container);
            container.Configure(x => x.For<IServiceLocator>().Singleton().Use(serviceLocator));

            ServiceLocator.SetLocatorProvider(() => serviceLocator);
        }
Beispiel #10
0
        public static void Initialize()
        {
            // This works because MVC invoked StructuremapMvc.Start,
            // which invoked StructureMapDependencyScopeFactory to create
            // a container at startup.
            // The trouble with it is that StructuremapMvc.StructureMapDependencyScope
            // is highly dependent on Http context, hence must remain in App.Application
            // and cannot be moved down to a more generally available App.Infrastrucute
            // so that other modules can get to it.
            // The trick is to Add a line to StructuremapMvc (since it is decorated with
            // "Start" and will be invoked by MVC before we get to this) to cache the container
            // in an App specific Static property that this class can get to.

            var container = StructureMapContainerLocator.Container;
            var locator   = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => locator);

            string whatDidIScan = container.WhatDidIScan();

            // Write to debug so it shows on Console while developing:
            Debug.WriteLine("ServiceLocator Configuration Summary");
            Debug.WriteLine("====================================");
            Debug.WriteLine(whatDidIScan);


            // But I think (todo) the above is to another channel.
            // So write it to the trace so that it ends in diagnostics logs:
            var diagnosticsTracingService = AppDependencyLocator.Current.GetInstance <IDiagnosticsTracingService>();

            diagnosticsTracingService.Trace(TraceLevel.Verbose, "ServiceLocator Configuration Summary");
            diagnosticsTracingService.Trace(TraceLevel.Verbose, "====================================");
            diagnosticsTracingService.Trace(TraceLevel.Verbose, whatDidIScan);
        }
        public void should_get_all_instances_for_a_given_type()
        {
            IEnumerable<object> instances = new StructureMapServiceLocator(container)
                .GetAllInstances(typeof (ISecurityContext));

            instances.Single(i => i.GetType() == typeof (WebSecurityContext));
            instances.Single(i => ReferenceEquals(i, _mockSecurityContext));
        }
        public void should_get_all_instances_for_a_given_type()
        {
            IEnumerable <object> instances = new StructureMapServiceLocator(container)
                                             .GetAllInstances(typeof(ISecurityContext));

            instances.Single(i => i.GetType() == typeof(WebSecurityContext));
            instances.Single(i => ReferenceEquals(i, _mockSecurityContext));
        }
 public void before_each()
 {
     serviceLocator = new StructureMapServiceLocator();
     shellView = MockRepository.GenerateStub<IShellView>();
     logSourcePresenter = MockRepository.GenerateMock<ILogSourcePresenter>();
     logProvider = MockRepository.GenerateStub<ILogProvider>();
     ObjectFactory.Initialize(
         x => x.ForRequestedType<ILogSourcePresenter>().TheDefault.IsThis(logSourcePresenter));
 }
Beispiel #14
0
        public void should_set_service_locator_on_fubu_page()
        {
            var serviceLocator = new StructureMapServiceLocator(container);

            container.Inject <IServiceLocator>(serviceLocator);
            var fubuPage = container.GetInstance <FubuPage>();

            fubuPage.ServiceLocator.ShouldEqual(serviceLocator);
        }
 public void CallsInitialize()
 {
     var called = false;
     var locator = new StructureMapServiceLocator();
     locator.Initialize = (type) => { called = true; };
     locator.RegisterDependencies();
     called.ShouldBeTrue();
     locator.Reset();
 }
Beispiel #16
0
 private void SetupStructureMap()
 {
     var registry = new StructureMapRegistry();
     var container = new Container(registry);
     var structureMapServiceLocator = new StructureMapServiceLocator(container);
     ServiceLocator.SetLocatorProvider(() => structureMapServiceLocator);
     var locator = new StructureMapServiceLocatorControllerFactory();
     ControllerBuilder.Current.SetControllerFactory(locator);
 }
 public void GetsInstanceNamesFor()
 {
     var locator = new StructureMapServiceLocator();
     locator.EnsureDependenciesRegistered();
     var impl = locator.GetInstanceNamesFor<ISimpleInterface>();
     impl.Count().ShouldEqual(1);
     impl.First().ShouldEqual("Postback.Blog.Tests.DI.SimpleInterface, Postback.Blog.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
     locator.Reset();
 }
 public void EnsuresDependenciesRegistered()
 {
     var callsInitialize = false;
     var locator = new StructureMapServiceLocator();
     locator.Reset();
     locator.Initialize = (type) => { callsInitialize = true; };
     locator.EnsureDependenciesRegistered();
     callsInitialize.ShouldBeTrue();
     locator.Reset();
 }
Beispiel #19
0
        public Using_UserService()
        {
            ConnectionProvider.NewConnection = connectionString => new SqlConnection(ConnectionStringProvider.GetConnectionString());
            var container = new Container();
            container.Configure(c => c.For<IDbConnection>()
                                      .Use(ConnectionProvider.GetConnection));

            var serviceLocator = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => serviceLocator);
        }
        public static void Start()
        {
            IContainer container = IoC.Initialize();

            StructureMapDependencyScope = new StructureMapDependencyScope(container);
            DependencyResolver.SetResolver(StructureMapDependencyScope);
            DynamicModuleUtility.RegisterModule(typeof(StructureMapScopeModule));
            var smServiceLocator = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => smServiceLocator);
        }
Beispiel #21
0
        private void SetupStructureMap()
        {
            var registry  = new StructureMapRegistry();
            var container = new Container(registry);
            var structureMapServiceLocator = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => structureMapServiceLocator);
            var locator = new StructureMapServiceLocatorControllerFactory();

            ControllerBuilder.Current.SetControllerFactory(locator);
        }
        public void RegistersDependencies()
        {
            try{
            var locator = new StructureMapServiceLocator();
            locator.RegisterDependencies();
            locator.Reset();
                }catch(Exception ex)
                {
                    true.ShouldBeFalse();
                }

            true.ShouldBeTrue();
        }
Beispiel #23
0
		internal static void StartMVCInternal(RoadkillRegistry registry, bool isWeb)
		{
			IContainer container = new Container(c =>
			{
				c.AddRegistry(registry);
				c.AddRegistry(new LightSpeedRegistry());
			});

			Locator = new StructureMapServiceLocator(container, isWeb);

			// MVC locator
			DependencyResolver.SetResolver(Locator);
			DynamicModuleUtility.RegisterModule(typeof(StructureMapHttpModule));
		}
Beispiel #24
0
        internal static void StartMVCInternal(RoadkillRegistry registry, bool isWeb)
        {
            IContainer container = new Container(c =>
            {
                c.AddRegistry(registry);
                c.AddRegistry(new LightSpeedRegistry());
            });

            Locator = new StructureMapServiceLocator(container, isWeb);

            // MVC locator
            DependencyResolver.SetResolver(Locator);
            DynamicModuleUtility.RegisterModule(typeof(StructureMapHttpModule));
        }
Beispiel #25
0
        public void Setup()
        {
            this.Container = new Container();
            this.Container.Configure(c => c.ForSingletonOf<IDomainEventService>().Use<DomainEventService>());
            Container.Configure(x => x.Scan(scanner =>
            {
                scanner.AssembliesFromApplicationBaseDirectory();
                scanner.ConnectImplementationsToTypesClosing(typeof(IRuleCollection<>));
                scanner.WithDefaultConventions();
            }));

            var structureMapServiceLocator = new StructureMapServiceLocator(Container);
            ServiceLocator.SetLocatorProvider(() => structureMapServiceLocator);
        }
Beispiel #26
0
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;

            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            serializerSettings.Converters.Add(new StringEnumConverter {
                CamelCaseText = true
            });

            var locatorProvider = new StructureMapServiceLocator(StructureMapContainerProvider.GetContainer());

            ServiceLocator.SetLocatorProvider(() => locatorProvider);
            config.DependencyResolver = new DependencyResolver();
        }
Beispiel #27
0
    private static IContainer RegisterIoc()
    {
        var container = new Container(cfg => cfg.Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.LookForRegistries();
        }));

        var serviceLocator         = new StructureMapServiceLocator(container);
        var serviceLocatorProvider = new ServiceLocatorProvider(() => serviceLocator);

        container.Configure(cfg => cfg.For <ServiceLocatorProvider>().Use(serviceLocatorProvider));

        return(container);
    }
Beispiel #28
0
        /// <summary>
        /// 注册调用的主入口
        /// </summary>
        /// <param name="moreMap">其他注册,在正常的注册完成后,会执行该方法,做其他的注册</param>
        public static void Bootstrap(Action <IRegistration> moreMap = null)
        {
            var locator = new StructureMapServiceLocator();

            locator.UseAsDefault();
            locator.Map(() => ServiceLocator.Current);
            locator.Logger.Log("Configuring Registries");

            locator.Map <IRegistration>(() => locator);
            locator.Map <ICacheProvider, CacheManager>().Singleton();
            locator.ScanAssembly().ExtensionRegister();
            moreMap?.Invoke(locator);
            locator.Logger.Log("Loading container...");
            locator.Load();
            locator.Logger.Log("Done");
        }
        public override void Given()
        {
            _token = "token";
            _authenticationTokenRequest = new AuthenticationTokenRequest {
                authToken = _token
            };

            _request = MockFor <IFubuRequest>();
            _request.Stub(a => a.Get <AuthenticationTokenRequest>()).Return(_authenticationTokenRequest);

            _request.Stub(a => a.Get <ICurrentSDKUser>()).Return(MockFor <ICurrentSDKUser>());

            var services = new StructureMapServiceLocator(_services.Container);

            _context = new FubuRequestContext(services, MockFor <IHttpRequest>(), _request, MockFor <IOutputWriter>(), MockFor <FubuCore.Logging.ILogger>());
        }
Beispiel #30
0
        public void TestIOC()
        {
            var locator = new StructureMapServiceLocator();

            locator.UseAsDefault();
            locator.Map(() => ServiceLocator.Current);
            locator.Map <ITry, Try>();
            locator.Map <ITryBase, TryBase>();
            locator.Load();

            var myTry  = ServiceLocator.Current.GetInstance <ITry>();
            var str    = "Hello world!";
            var result = myTry.DoSome(str);

            myTry.GetSome("12");
        }
        public StructureMapTests()
        {
            var container = new Container(cfg =>
                cfg.Scan(scanner =>
                {
                    scanner.AssemblyContainingType<A>();
                    scanner.WithDefaultConventions();
                    scanner.RegisterConcreteTypesAgainstTheFirstInterface();
                    scanner.AddAllTypesOf(typeof (B<>));
                    scanner.AddAllTypesOf(typeof (C<,>));
                    scanner.AddAllTypesOf(typeof(D<>));
                    scanner.AddAllTypesOf(typeof(E<,>));
                    scanner.AddAllTypesOf(typeof(F<,>));
                })
                );

            ServiceLocator = new StructureMapServiceLocator(container);
        }
Beispiel #32
0
        /// <summary>
        /// 注册调用的主入口
        /// </summary>
        /// <param name="moreMap">其他注册,在正常的注册完成后,会执行该方法,做其他的注册</param>
        public static void Bootstrap(Action <IRegistration> moreMap = null)
        {
            var locator = new StructureMapServiceLocator();

            locator.UseAsDefault();
            locator.Map(() => ServiceLocator.Current);
            locator.Logger.Log("Configuring Registries");

            locator.Map <IRegistration>(() => locator);
            locator.ScanAssembly().ExtensionRegister();
            if (moreMap != null)
            {
                moreMap(locator);
            }
            locator.Logger.Log("Loading container...");
            locator.Load();
            locator.Logger.Log("Done");
        }
Beispiel #33
0
        /// <summary>
        /// 注册调用的主入口
        /// </summary>
        /// <param name="moreMap">其他注册,在正常的注册完成后,会执行该方法,做其他的注册</param>
        public static void Bootstrap(Action <IRegistration> moreMap = null)
        {
            var locator = new StructureMapServiceLocator();

            locator.UseAsDefault();
            locator.Map(() => ServiceLocator.Current);
            locator.Logger.Log("Configuring Registries");

            locator.Map <IRegistration>(() => locator);
            locator.Map <ICacheProvider, CacheManager>().Singleton();
            locator.UseBusinessLayer().UseDataAccessLayer();
            if (moreMap != null)
            {
                moreMap(locator);
            }
            locator.Logger.Log("Loading container...");
            locator.Load();
            locator.Logger.Log("Done");
        }
Beispiel #34
0
        public IoCHandlerTests()
        {
            var serviceLocator = new StructureMapServiceLocator(new Container(c => c.Scan(s =>
            {
                s.TheCallingAssembly();
                s.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandle<,>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandleAsync<>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandleAsync<,>));
                s.WithDefaultConventions();
            })));

            _dependencyResolver = new CommonServiceLocatorDependencyResolver(serviceLocator);

            _dispatcher = AppDispatcherFactory.Create(app =>
            {
                app.UseDependencyResolver(_dependencyResolver);
            });
        }
Beispiel #35
0
        public IoCHandlerTests()
        {
            var serviceLocator = new StructureMapServiceLocator(new Container(c => c.Scan(s =>
            {
                s.TheCallingAssembly();
                s.ConnectImplementationsToTypesClosing(typeof(IHandle <>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandle <,>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandleAsync <>));
                s.ConnectImplementationsToTypesClosing(typeof(IHandleAsync <,>));
                s.WithDefaultConventions();
            })));

            _dependencyResolver = new CommonServiceLocatorDependencyResolver(serviceLocator);

            _dispatcher = AppDispatcherFactory.Create(app =>
            {
                app.UseDependencyResolver(_dependencyResolver);
            });
        }
Beispiel #36
0
        /// <summary>
        /// Initializes the service locator.
        /// </summary>
        static void InitializeServiceLocator()
        {
            var container = new StructureMap.Container();
            var locator   = new StructureMapServiceLocator(container);
            var context   = new ServiceConfigurationContext(HostType.Installer, new StructureMapConfiguration(container));

            context.Services.AddSingleton <IRequiredMetaFieldCollection, NoRequiredMetaFields>();
            context.Services.AddSingleton <IWarehouseRepository, WarehouseRepositoryDatabase>();
            context.Services.AddSingleton <ISynchronizedObjectInstanceCache, LocalCacheWrapper>();
            context.Services.AddSingleton <ICatalogSystem>(locate => CatalogContext.Current);
            context.Services.AddSingleton <IChangeNotificationManager, NullChangeNotificationManager>();
            context.Services.AddSingleton <IPriceService, PriceServiceDatabase>();

            context.Services.AddTransient <SecurityContext>(locate => SecurityContext.Current);
            context.Services.AddTransient <CustomerContext>(locate => CustomerContext.Current);
            context.Services.AddTransient <FrameworkContext>(locate => FrameworkContext.Current);

            ServiceLocator.SetLocator(locator);
        }
        public void SetUp()
        {
            var theHttpRequest = MockRepository.GenerateMock<ICurrentChain>();
            theHttpRequest.Stub(x => x.ResourceHash()).Return("something/else");

            var locator = new StructureMapServiceLocator(new Container(x =>
            {
                x.For<ICurrentChain>().Use(theHttpRequest);
            }));

            FubuApplication.SetupNamingStrategyForHttpHeaders();

            var data = new InMemoryRequestData();
            data["If-None-Match"] = "12345";

            var context = new BindingContext(data, locator, new NulloBindingLogger());

            var binder = StandardModelBinder.Basic();

            theEtagRequest =  binder.Bind(typeof(ETaggedRequest), context).As<ETaggedRequest>();
        }
        public void SetUp()
        {
            var theHttpRequest = MockRepository.GenerateMock <ICurrentChain>();

            theHttpRequest.Stub(x => x.ResourceHash()).Return("something/else");

            var locator = new StructureMapServiceLocator(new Container(x =>
            {
                x.For <ICurrentChain>().Use(theHttpRequest);
            }));

            FubuApplication.SetupNamingStrategyForHttpHeaders();

            var data = new InMemoryRequestData();

            data["If-None-Match"] = "12345";

            var context = new BindingContext(data, locator, new NulloBindingLogger());

            var binder = StandardModelBinder.Basic();

            theEtagRequest = binder.Bind(typeof(ETaggedRequest), context).As <ETaggedRequest>();
        }
Beispiel #39
0
        public static void Test()
        {
            var locator = new StructureMapServiceLocator(null, new LogInterceptor());

            locator.Map <IRegistration>(() => locator);
            //locator.Map(() => ServiceLocator.Current);
            locator.UseAsDefault();
            //locator.Map<IA, A>();
            //locator.Map<IB, B>("B");
            //locator.Map<IC, C>();
            //locator.Map<IB, D>("D");
            locator.ScanAssembly <IocTest>();
            locator.Map <E, E>();
            locator.Load();
            locator.GetInstance <IA>().Write();
            ServiceLocator.Current.GetInstance <IA>().Sing();
            var instances = ServiceLocator.Current.GetAllInstances <IB>();

            foreach (var instance in instances)
            {
                instance.Write();
            }
        }
Beispiel #40
0
        public ApplicationContext GetAppContext()
        {
            _container.Configure(c => c.AddRegistry <DefaultRegistry>());
            Debug.WriteLine(_container.WhatDidIScan());
            _container.Inject <ApplicationContext>(new AppContext(_container));
            _container.GetInstance <ITranslationService>().Reload();

            var locator = new StructureMapServiceLocator(_container);

            ServiceLocator.SetLocatorProvider(() => locator);

            _exportProvider = new CSLExportProvider(locator);
            var appController = _container.GetInstance <IApplicationController>();

            _exportProvider.RegisterType(appController.GetType());

            //var bindings = _container.GetAllInstances<IApplicationController>().ToList();
            //bindings.ForEach(m => _exportProvider.RegisterType(m.GetType()));

            MefContainer.AddExportProvider(_exportProvider);

            return(_container.GetInstance <ApplicationContext>());
        }
        public static void ConfigureWith(string assemblyDirectory, string rootNamespace)
        {
            if (_configured) return;

            if (CustomScanner.IsNull()) CustomScanner = s => { };

            if (Interceptors.IsNull()) Interceptors = x => { };

            var container = new Container();

            var serviceLocator = new StructureMapServiceLocator(container);

            ServiceLocator.SetLocatorProvider(() => serviceLocator);

            container.Configure(x =>
                                {
                                    x.For<IContainer>()
                                     .Use(container);
                                    x.For<IServiceLocator>()
                                     .Singleton()
                                     .Use(serviceLocator);
                                    Interceptors(x);
                                    x.Scan(s =>
                                           {
                                               if (assemblyDirectory.IsNotBlank() && rootNamespace.IsNotBlank())
                                               {
                                                   s.AssembliesFromPath(assemblyDirectory, assembly => assembly.GetName()
                                                                                                               .Name.StartsWith(rootNamespace));
                                               }
                                               s.WithDefaultConventions();
                                               s.LookForRegistries();
                                               CustomScanner(s);
                                           });
                                });

            _configured = true;
        }
 public StructureMapServiceLocatorTests()
 {
     _structureMapServiceLocator = new StructureMapServiceLocator(StructureMapContainerProvider.GetContainer());
     ServiceLocator.SetLocatorProvider(() => _structureMapServiceLocator);
 }
        public void should_set_service_locator_on_fubu_page()
        {
            var serviceLocator = new StructureMapServiceLocator(container);
            container.Inject<IServiceLocator>(serviceLocator);
            var fubuPage = container.GetInstance<FubuPage>();

            fubuPage.ServiceLocator.ShouldEqual(serviceLocator);
        }
Beispiel #44
0
 public void SetUp()
 {
     stringifier = new Stringifier();
     container = new Container();
     locator = new StructureMapServiceLocator(container);
 }
Beispiel #45
0
 public void SetUp()
 {
     stringifier = new Stringifier();
     container   = new Container();
     locator     = new StructureMapServiceLocator(container);
 }
 public void GetsServiceByType()
 {
     var locator = new StructureMapServiceLocator();
     locator.EnsureDependenciesRegistered();
     var impl = locator.GetService(typeof(ISimpleInterface));
     impl.ShouldBeInstanceOfType(typeof(SimpleInterface));
     locator.Reset();
 }
        public void GetsInstanceByTypeAndKey()
        {
            var locator = new StructureMapServiceLocator();
            locator.EnsureDependenciesRegistered();
            var impl = locator.GetInstance(typeof(IOtherInterface), "bar");
            impl.ShouldBeInstanceOfType(typeof(OtherOtherInterface));

            locator.Reset();
        }
 public void GetsAllInstancesByType()
 {
     var locator = new StructureMapServiceLocator();
     locator.EnsureDependenciesRegistered();
     var items = locator.GetAllInstances(typeof(IFakeInterface));
     items.Count().ShouldEqual(2);
     locator.Reset();
 }
 public void GivenIHaveAStructureMapServiceLocator()
 {
     IServiceLocator serviceLocator = new StructureMapServiceLocator();
     UseThisServiceLocator(serviceLocator);
 }
 public void GenericGetAll()
 {
     var locator = new StructureMapServiceLocator();
     locator.EnsureDependenciesRegistered();
     var items = locator.GetAllInstances<IFakeInterface>();
     items.Count().ShouldEqual(2);
     locator.Reset();
 }
		/// <summary>
		/// Creates a new instance of MocksAndStubsContainer.
		/// </summary>
		/// <param name="useCacheMock">The 'Roadkill' MemoryCache is used by default, but as this is static it can have problems with 
		/// the test runner unless you clear the Container.MemoryCache on setup each time, but then doing that doesn't give a realistic 
		/// reflection of how the MemoryCache is used inside an ASP.NET environment.</param>
		public MocksAndStubsContainer(bool useCacheMock = false)
		{
			ApplicationSettings = new ApplicationSettings();
			ApplicationSettings.Installed = true;
			ApplicationSettings.AttachmentsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "attachments");
			ConfigReaderWriter = new ConfigReaderWriterStub();

			// Cache
			MemoryCache = useCacheMock ? new CacheMock() : CacheMock.RoadkillCache;
			ListCache = new ListCache(ApplicationSettings, MemoryCache);
			SiteCache = new SiteCache(MemoryCache);
			PageViewModelCache = new PageViewModelCache(ApplicationSettings, MemoryCache);

			// Repositories
			SettingsRepository = new SettingsRepositoryMock();
			SettingsRepository.SiteSettings = new SiteSettings();
			SettingsRepository.SiteSettings.MarkupType = "Creole";
			UserRepository = new UserRepositoryMock();
			PageRepository = new PageRepositoryMock();
			InstallerRepository = new InstallerRepositoryMock();

			RepositoryFactory = new RepositoryFactoryMock()
			{
				SettingsRepository = SettingsRepository,
				UserRepository = UserRepository,
				PageRepository = PageRepository,
				InstallerRepository = InstallerRepository
			};
			DatabaseTester = new DatabaseTesterMock();

			// Plugins
			PluginFactory = new PluginFactoryMock();
			MarkupConverter = new MarkupConverter(ApplicationSettings, SettingsRepository, PageRepository, PluginFactory);

			// Services
			// Dependencies for PageService. Be careful to make sure the class using this Container isn't testing the mock.
			SettingsService = new SettingsService(RepositoryFactory, ApplicationSettings);
			UserService = new UserServiceMock(ApplicationSettings, UserRepository);
			UserContext = new UserContext(UserService);
			SearchService = new SearchServiceMock(ApplicationSettings, SettingsRepository, PageRepository, PluginFactory);
			SearchService.PageContents = PageRepository.PageContents;
			SearchService.Pages = PageRepository.Pages;
			HistoryService = new PageHistoryService(ApplicationSettings, SettingsRepository, PageRepository, UserContext,
				PageViewModelCache, PluginFactory);
			FileService = new FileServiceMock();
			PageService = new PageService(ApplicationSettings, SettingsRepository, PageRepository, SearchService, HistoryService,
				UserContext, ListCache, PageViewModelCache, SiteCache, PluginFactory);

			StructureMapContainer = new Container(x =>
			{
				x.AddRegistry(new TestsRegistry(this));
			});

			Locator = new StructureMapServiceLocator(StructureMapContainer, false);

			InstallationService = new InstallationService((databaseName, connectionString) =>
			{
				InstallerRepository.DatabaseName = databaseName;
				InstallerRepository.ConnectionString = connectionString;

				return InstallerRepository;
			}, Locator);

			// EmailTemplates
			EmailClient = new EmailClientMock();
		}
        public void GenericGetWithKey()
        {
            var locator = new StructureMapServiceLocator();
            locator.EnsureDependenciesRegistered();

            var impl = locator.GetInstance<IOtherInterface>("foo");
            impl.ShouldBeInstanceOfType(typeof(OtherInterface));

            bool thrown = false;
            try
            {
                var nullimpl = locator.GetInstance<IOtherInterface>("test");
            }
            catch (Exception ex)
            {
                thrown = true;
                ex.ShouldBeInstanceOfType(typeof(StructureMapException));
            }

            thrown.ShouldBeTrue();
            locator.Reset();
        }
        public void SetUp()
        {
            var container = new Container();
            var locator = new StructureMapServiceLocator(container);

            finder = new ServiceEnabledObjectConverter(locator);
        }
Beispiel #54
0
        /// <summary>
        /// Creates a new instance of MocksAndStubsContainer.
        /// </summary>
        /// <param name="useCacheMock">The 'Roadkill' MemoryCache is used by default, but as this is static it can have problems with
        /// the test runner unless you clear the Container.MemoryCache on setup each time, but then doing that doesn't give a realistic
        /// reflection of how the MemoryCache is used inside an ASP.NET environment.</param>
        public MocksAndStubsContainer(bool useCacheMock = false)
        {
            ApplicationSettings                   = new ApplicationSettings();
            ApplicationSettings.Installed         = true;
            ApplicationSettings.AttachmentsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "attachments");
            ConfigReaderWriter = new ConfigReaderWriterStub();

            // Cache
            MemoryCache        = useCacheMock ? new CacheMock() : CacheMock.RoadkillCache;
            ListCache          = new ListCache(ApplicationSettings, MemoryCache);
            SiteCache          = new SiteCache(MemoryCache);
            PageViewModelCache = new PageViewModelCache(ApplicationSettings, MemoryCache);

            // Repositories
            SettingsRepository = new SettingsRepositoryMock();
            SettingsRepository.SiteSettings            = new SiteSettings();
            SettingsRepository.SiteSettings.MarkupType = "Creole";
            UserRepository      = new UserRepositoryMock();
            PageRepository      = new PageRepositoryMock();
            InstallerRepository = new InstallerRepositoryMock();

            RepositoryFactory = new RepositoryFactoryMock()
            {
                SettingsRepository  = SettingsRepository,
                UserRepository      = UserRepository,
                PageRepository      = PageRepository,
                InstallerRepository = InstallerRepository
            };
            DatabaseTester = new DatabaseTesterMock();

            // Plugins
            PluginFactory   = new PluginFactoryMock();
            MarkupConverter = new MarkupConverter(ApplicationSettings, SettingsRepository, PageRepository, PluginFactory);

            // Services
            // Dependencies for PageService. Be careful to make sure the class using this Container isn't testing the mock.
            SettingsService            = new SettingsService(RepositoryFactory, ApplicationSettings);
            UserService                = new UserServiceMock(ApplicationSettings, UserRepository);
            UserContext                = new UserContext(UserService);
            SearchService              = new SearchServiceMock(ApplicationSettings, SettingsRepository, PageRepository, PluginFactory);
            SearchService.PageContents = PageRepository.PageContents;
            SearchService.Pages        = PageRepository.Pages;
            HistoryService             = new PageHistoryService(ApplicationSettings, SettingsRepository, PageRepository, UserContext,
                                                                PageViewModelCache, PluginFactory);
            FileService = new FileServiceMock();
            PageService = new PageService(ApplicationSettings, SettingsRepository, PageRepository, SearchService, HistoryService,
                                          UserContext, ListCache, PageViewModelCache, SiteCache, PluginFactory);

            StructureMapContainer = new Container(x =>
            {
                x.AddRegistry(new TestsRegistry(this));
            });

            Locator = new StructureMapServiceLocator(StructureMapContainer, false);

            InstallationService = new InstallationService((databaseName, connectionString) =>
            {
                InstallerRepository.DatabaseName     = databaseName;
                InstallerRepository.ConnectionString = connectionString;

                return(InstallerRepository);
            }, Locator);

            // EmailTemplates
            EmailClient = new EmailClientMock();
        }