public IVersionControlSystem Get(ISourceControlConnectionSettingsSource settings)
        {
            var vcsArgs = new ExplicitArguments();

            vcsArgs.Set(settings);
            return(ObjectFactory.GetInstance <IVersionControlSystem>(vcsArgs));
        }
Exemple #2
0
        /// <summary>
        /// Configures the common container.
        /// </summary>
        /// <param name="configurationExpression">The configuration expression.</param>
        private static void ConfigureCommonContainer(ConfigurationExpression configurationExpression)
        {
            String connString     = Program.Configuration.GetValue <String>("EventStoreSettings:ConnectionString");
            String connectionName = Program.Configuration.GetValue <String>("EventStoreSettings:ConnectionName");
            Int32  httpPort       = Program.Configuration.GetValue <Int32>("EventStoreSettings:HttpPort");

            EventStoreConnectionSettings settings = EventStoreConnectionSettings.Create(connString, connectionName, httpPort);

            configurationExpression.For <IEventStoreContext>().Use <EventStoreContext>().Singleton().Ctor <EventStoreConnectionSettings>().Is(settings);

            Func <String, IEventStoreContext> eventStoreContextFunc = (connectionString) =>
            {
                EventStoreConnectionSettings connectionSettings = EventStoreConnectionSettings.Create(connectionString, connectionName, httpPort);

                ExplicitArguments args = new ExplicitArguments().Set(connectionSettings);

                return(Bootstrapper.Container.GetInstance <IEventStoreContext>(args));
            };

            configurationExpression.For <Func <String, IEventStoreContext> >().Use(eventStoreContextFunc);

            Func <EventStoreConnectionSettings, IEventStoreConnection> eventStoreConnectionFunc = (connectionSettings) =>
            {
                return(EventStoreConnection.Create(connectionSettings.ConnectionString));
            };

            configurationExpression.For <Func <EventStoreConnectionSettings, IEventStoreConnection> >().Use(eventStoreConnectionFunc);
        }
        public T Get <T>(ExplictArg explictArg)
        {
            var args = new ExplicitArguments();

            args.SetArg(explictArg.Key, explictArg.Arg);
            return(_container.GetInstance <T>(args));
        }
 public AutoFactoryMethodDefinition(AutoFactoryMethodType methodType, Type instanceType, string instanceName, ExplicitArguments explicitArguments)
 {
     MethodType        = methodType;
     InstanceType      = instanceType;
     InstanceName      = instanceName;
     ExplicitArguments = explicitArguments;
 }
Exemple #5
0
        private ISignalRService <TDto, TRequest> BuildInternal(params object[] parameters)
        {
            var args = new ExplicitArguments();

            foreach (var @param in parameters)
            {
                args.Set(@param.GetType(), @param);
            }

            if (!args.Defaults.ContainsKey(typeof(Action <HttpConnectionOptions>)))
            {
                args.Defaults.Add(typeof(Action <HttpConnectionOptions>), new Action <HttpConnectionOptions>((_) => { }));
            }

            if (!args.Defaults.ContainsKey(typeof(HttpTransportType)))
            {
                args.Defaults.Add(typeof(HttpTransportType), HttpTransportType.WebSockets | HttpTransportType.LongPolling | HttpTransportType.ServerSentEvents);
            }

            var service = AppCore.Instance.ObjectProvider.GetInstance <ISignalRService <TDto, TRequest> >(args);

            service.BuildInternal();

            return(service);
        }
		public IVersionControlSystem Get(IStorageRepository profile)
		{
			var vcsArgs = new ExplicitArguments();
			vcsArgs.Set(profile.GetProfile<ISourceControlConnectionSettingsSource>());
			vcsArgs.Set(profile);
			return ObjectFactory.GetInstance<IVersionControlSystem>(vcsArgs);
		}
 public AutoFactoryMethodDefinition(AutoFactoryMethodType methodType, Type instanceType, string instanceName, ExplicitArguments explicitArguments)
 {
     MethodType = methodType;
     InstanceType = instanceType;
     InstanceName = instanceName;
     ExplicitArguments = explicitArguments;
 }
Exemple #8
0
        public IPresenter Create(Type presenterType, Type viewType, IView viewInstance)
        {
            if (presenterType == null)
            {
                throw new ArgumentNullException("presenterType");
            }
            if (viewType == null)
            {
                throw new ArgumentNullException("viewType");
            }
            if (viewInstance == null)
            {
                throw new ArgumentNullException("viewInstance");
            }

            if (!container.Model.HasImplementationsFor(presenterType))
            {
                lock (registerLock)
                {
                    if (!container.Model.HasImplementationsFor(presenterType))
                    {
                        container.Configure(x => x.For(presenterType).HybridHttpOrThreadLocalScoped().Use(presenterType).Named(presenterType.Name));
                    }
                }
            }

            var args = new ExplicitArguments();

            args.Set("view");
            args.SetArg("view", viewInstance);

            return((IPresenter)container.GetInstance(presenterType, args));
        }
        public static ExplicitArguments ToExplicitArgs(this ServiceArguments arguments)
        {
            var explicits = new ExplicitArguments();
            arguments.EachService(explicits.Set);

            return explicits;
        }
        public void supply_defaults_with_args()
        {
            var container = new Container(x =>
            {
                x.For<IWidget>().Use<BWidget>();
                x.For<IService>().Use<AService>();
            });

            // SAMPLE: explicit-use-explicit-args
            var widget = new BWidget();
            var service = new BService();

            var args = new ExplicitArguments();
            args.Set<IWidget>(widget);
            args.Set<IService>(service);

            var guyWithWidgetAndService = container
                .GetInstance<GuyWithWidgetAndService>(args);

            guyWithWidgetAndService
                .Widget.ShouldBeTheSameAs(widget);

            guyWithWidgetAndService
                .Service.ShouldBeTheSameAs(service);
            // ENDSAMPLE
        }
        public void supply_defaults_with_args()
        {
            var container = new Container(x =>
            {
                x.For <IWidget>().Use <BWidget>();
                x.For <IService>().Use <AService>();
            });

            // SAMPLE: explicit-use-explicit-args
            var widget  = new BWidget();
            var service = new BService();

            var args = new ExplicitArguments();

            args.Set <IWidget>(widget);
            args.Set <IService>(service);

            var guyWithWidgetAndService = container
                                          .GetInstance <GuyWithWidgetAndService>(args);

            guyWithWidgetAndService
            .Widget.ShouldBeTheSameAs(widget);

            guyWithWidgetAndService
            .Service.ShouldBeTheSameAs(service);
            // ENDSAMPLE
        }
Exemple #12
0
        /// <summary>
        /// Отправляем сообщение посредством EventAggregator что нам нужно установить
        /// такой набор временных отметок в отпределенное время.
        /// </summary>
        /// <param name="timesList"></param>
        private async void SendUpdateAtTimes(List <string> timesList)
        {
            // Если вызов идет во время инициалзации - выходим из метода
            if (!_useNormalWork)
            {
                return;
            }

            var args = new ExplicitArguments();

            args.SetArg("fileName", _playFileAtTime);
            args.SetArg("tsLists", timesList);
            IAtTimePlayData atData = _container.GetInstance <IAtTimePlayData>(args);

            var argMsg = new ExplicitArguments();

            argMsg.SetArg("msgData", atData);
            var atMessage = _container.GetInstance <IAtTimePlayDataMsg>(argMsg);

            SendToAclockMessage(null, atData);

            //mediator.Publish(atMessage);
            // Пробуем запросить нашего работника, в если удачно - пересылаему ему задачу
            var atHandle = _container.TryGetInstance <IHandle <IAtTimePlayDataMsg> >();

            if (atHandle != null)
            {
                await _eventAggregator.PublishOnUIThreadAsync(atMessage);
            }
        }
        public IPresenter Create(Type presenterType, Type viewType, IView viewInstance)
        {
            if (presenterType == null)
                throw new ArgumentNullException("presenterType");
            if (viewType == null)
                throw new ArgumentNullException("viewType");
            if (viewInstance == null)
                throw new ArgumentNullException("viewInstance");

            if (!container.Model.HasImplementationsFor(presenterType))
            {
                lock (registerLock)
                {
                    if (!container.Model.HasImplementationsFor(presenterType))
                    {
                        container.Configure(x => x.For(presenterType).HybridHttpOrThreadLocalScoped().Use(presenterType).Named(presenterType.Name));
                    }
                }
            }

            var args = new ExplicitArguments();
            args.Set("view");
            args.SetArg("view", viewInstance);

            return (IPresenter)container.GetInstance(presenterType, args);
        }
        public ITabContentLifetimeHost RestoreTabContent(LayoutStructureTabItem tabItem)
        {
            var  connectionPropVal = tabItem.ReadProperty(ConnectionIdBackingStorePropertyName);
            Guid connectionId;
            ExplicitConnection explicitConnection = null;

            if (connectionPropVal != null && Guid.TryParse(connectionPropVal, out connectionId))
            {
                explicitConnection = _container.GetInstance <IExplicitConnectionCache>().Get(connectionId).ValueOrDefault();
            }

            var  fileIdPropVal = tabItem.ReadProperty(FileIdBackingStorePropertyName);
            Guid fileId;

            if (fileIdPropVal == null || !Guid.TryParse(fileIdPropVal, out fileId))
            {
                fileId = Guid.NewGuid();
            }

            var explicitArguments = new ExplicitArguments();

            explicitArguments.Set(typeof(Guid), fileId);
            explicitArguments.Set(typeof(ExplicitConnection), explicitConnection);

            var tabViewModel = _container.GetInstance <QueryDeveloperViewModel>(explicitArguments);

            PopulateDocument(tabViewModel);
            var disposable = Watch(tabViewModel);

            return(new TabContentLifetimeHost(tabViewModel, closeReason => Cleanup(closeReason, tabViewModel, disposable)));
        }
Exemple #15
0
        /// <summary>
        /// Gets the default instance of the pluginType using the explicitly configured arguments from the "args"
        /// </summary>
        /// <param name="pluginType"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public object GetInstance(Type pluginType, ExplicitArguments args)
        {
            Instance defaultInstance = _pipelineGraph.GetDefault(pluginType);
            string   requestedName   = Plugin.DEFAULT;

            return(buildInstanceWithArgs(pluginType, defaultInstance, args, requestedName));
        }
Exemple #16
0
        public static ExplicitArguments ToExplicitArgs(this Dependency[] dependencies)
        {
            var arguments = new ExplicitArguments();

            dependencies.ToList().ForEach(x => arguments.Set(x.Type, x.Instance));
            return(arguments);
        }
        /// <summary>
        /// Resolves the specified args.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="args">The args.</param>
        /// <returns>``0.</returns>
        public T Resolve <T>(IDictionary <string, object> args = null)
        {
            ExplicitArguments explicitArguments = new ExplicitArguments(args);

            return(args == null
                ? Container.GetInstance <T>()
                : Container.GetInstance <T>(explicitArguments));
        }
Exemple #18
0
 public SessionCache(IBuildSession resolver, ExplicitArguments arguments)
     : this(resolver)
 {
     if (arguments != null)
     {
         _defaults = arguments.Defaults;
     }
 }
Exemple #19
0
        public static ISignalRService <TDto, TRequest> GetSignalRService <TDto, TRequest>(this IAppContainer container, TRequest request)
            where TRequest : IHubRequest <TDto>
        {
            var explicitArg = new ExplicitArguments();

            explicitArg.Set(request);
            return(container.ObjectProvider.GetInstance <ISignalRService <TDto, TRequest> >(explicitArg));
        }
Exemple #20
0
        public IList <T> GetAllInstances <T>(ExplicitArguments args)
        {
            BuildSession session = withNewSession(Plugin.DEFAULT);

            args.RegisterDefaults(session);

            return(getListOfTypeWithSession <T>(session));
        }
        public IVersionControlSystem Get(IStorageRepository profile)
        {
            var vcsArgs = new ExplicitArguments();

            vcsArgs.Set(profile.GetProfile <ISourceControlConnectionSettingsSource>());
            vcsArgs.Set(profile);
            return(ObjectFactory.GetInstance <IVersionControlSystem>(vcsArgs));
        }
Exemple #22
0
        private static T GetService <T>(this IDependencyScope scope, params object[] arguments)
        {
            var container         = scope.GetService <IContainer>();
            var explicitArguments = new ExplicitArguments();

            arguments.ForEach(x => explicitArguments.Set(x.GetType(), x));
            return(container.GetInstance <T>(explicitArguments));
        }
        public static ExplicitArguments ToExplicitArgs(this ServiceArguments arguments)
        {
            var explicits = new ExplicitArguments();

            arguments.EachService((type, o) => explicits.Set(type, o));

            return(explicits);
        }
        public CommonRegistry()
        {
            String connString     = Startup.Configuration.GetValue <String>("EventStoreSettings:ConnectionString");
            String connectionName = Startup.Configuration.GetValue <String>("EventStoreSettings:ConnectionName");
            Int32  httpPort       = Startup.Configuration.GetValue <Int32>("EventStoreSettings:HttpPort");

            EventStoreConnectionSettings settings = EventStoreConnectionSettings.Create(connString, connectionName, httpPort);

            this.For <IEventStoreContext>().Use <EventStoreContext>().Singleton().Ctor <EventStoreConnectionSettings>().Is(settings);

            Func <String, IEventStoreContext> eventStoreContextFunc = (connectionString) =>
            {
                EventStoreConnectionSettings connectionSettings = EventStoreConnectionSettings.Create(connectionString, connectionName, httpPort);

                ExplicitArguments args = new ExplicitArguments().Set(connectionSettings);

                return(Startup.Container.GetInstance <IEventStoreContext>(args));
            };

            Func <EventStoreConnectionSettings, IEventStoreConnection> eventStoreConnectionFunc = (connectionSettings) =>
            {
                return(EventStoreConnection.Create(connectionSettings.ConnectionString));
            };

            this.For <IDomainEventHandler>().Use <GolfClubDomainEventHandler>().Named("GolfClub");
            this.For <IDomainEventHandler>().Use <GolfClubMembershipDomainEventHandler>().Named("GolfClubMembership");
            this.For <IDomainEventHandler>().Use <TournamentDomainEventHandler>().Named("Tournament");
            this.For <IDomainEventHandler>().Use <HandicapCalculationDomainEventHandler>().Named("HandicapCalculator");
            this.For <IDomainEventHandler>().Use <ReportingDomainEventHandler>().Named("Reporting");

            Func <String, IDomainEventHandler> domainEventHanderFunc = (name) => Startup.Container.GetInstance <IDomainEventHandler>(name);

            this.For <Func <EventStoreConnectionSettings, IEventStoreConnection> >().Use(eventStoreConnectionFunc);

            this.For <ESLogger.ILogger>().Use <ESLogger.Common.Log.ConsoleLogger>().Singleton();
            this.For <ICommandRouter>().Use <CommandRouter>().Singleton();
            this.For <IAggregateRepository <GolfClubAggregate> >()
            .Use <AggregateRepository <GolfClubAggregate> >().Singleton();
            this.For <IAggregateRepository <GolfClubMembershipAggregate> >()
            .Use <AggregateRepository <GolfClubMembershipAggregate> >().Singleton();
            this.For <IAggregateRepository <TournamentAggregate> >()
            .Use <AggregateRepository <TournamentAggregate> >().Singleton();
            this.For <IAggregateRepository <PlayerAggregate> >()
            .Use <AggregateRepository <PlayerAggregate> >().Singleton();
            this.For <IAggregateRepository <HandicapCalculationProcessAggregate> >()
            .Use <AggregateRepository <HandicapCalculationProcessAggregate> >().Singleton();

            this.For <IHandicapAdjustmentCalculatorService>().Use <HandicapAdjustmentCalculatorService>();
            //this.For<IManagmentAPIManager>().Use<ManagementAPIManager>().AlwaysUnique().Singleton();
            this.RegisterType <IManagmentAPIManager, ManagementAPIManager>().Singleton();
            this.For <IReportingManager>().Use <ReportingManager>().Singleton();
            this.For <ISecurityService>().Use <SecurityService>().Singleton();
            this.For <IGolfClubMembershipApplicationService>().Use <GolfClubMembershipApplicationService>().Singleton();
            this.For <ITournamentApplicationService>().Use <TournamentApplicationService>().Singleton();

            this.For <IHandicapCalculationProcessorService>().Use <HandicapCalculationProcessorService>().Transient();
        }
Exemple #25
0
        public static TPresenter GetPresenter <TPresenter>(object view)   //method wil be run each time a new view page is loaded
        {                                                                 //to resolve the required presenter and interfaces
            var explicitArguments = new ExplicitArguments();              //from the IOC container

            foreach (var implementedInterface in view.GetType().GetInterfaces())
            {
                explicitArguments.Set(implementedInterface, view);
            }
            return(Container.GetInstance <TPresenter>(explicitArguments));
        }
        private static ServiceHost PerCallServiceHostCreator(Type serviceType, Uri[] baseAddresses)
        {
            var args = new ExplicitArguments();

            args.Set(serviceType);
            args.Set(baseAddresses);
            var serviceHost = ObjectFactory.GetInstance <TelaWebServiceHost>(args);

            return(serviceHost);
        }
        public T Get <T>(IEnumerable <ExplictArg> explictArgs)
        {
            var args = new ExplicitArguments();

            foreach (var explictArg in explictArgs)
            {
                args.SetArg(explictArg.Key, explictArg.Arg);
            }
            return(_container.GetInstance <T>(args));
        }
Exemple #28
0
        private static ExplicitArguments CreateExplicitArguments(params object[] extraParameters)
        {
            var args = new ExplicitArguments();

            foreach (var parameter in extraParameters)
            {
                args.Set(parameter.GetType(), parameter);
            }
            return(args);
        }
Exemple #29
0
        public static TPresenter GetPresenter <TPresenter>(object view)
        {
            var explicitArguments = new ExplicitArguments();

            foreach (var implementedInterface in view.GetType().GetInterfaces())
            {
                explicitArguments.Set(implementedInterface, view);
            }
            return(Container.GetInstance <TPresenter>(explicitArguments));
        }
Exemple #30
0
        /// <summary>
        /// Gets all configured instances of type T using explicitly configured arguments from the "args"
        /// </summary>
        /// <param name="type"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public IList GetAllInstances(Type type, ExplicitArguments args)
        {
            BuildSession session = withNewSession(Plugin.DEFAULT);

            args.RegisterDefaults(session);

            Array instances = session.CreateInstanceArray(type, null);

            return(new ArrayList(instances));
        }
        public override void Execute <T>(ServiceArguments arguments, Action <T> action)
        {
            using (var nested = _container.GetNestedContainer())
            {
                var explicits = new ExplicitArguments();
                arguments.EachService(explicits.Set);

                action(nested.GetInstance <T>(explicits));
            }
        }
        private BuildSession(IPipelineGraph pipelineGraph, string requestedName, ExplicitArguments args,
                             Stack <Instance> buildStack)
        {
            this.pipelineGraph = pipelineGraph;

            _sessionCache = new SessionCache(this, args);

            RequestedName = requestedName ?? DEFAULT;

            _instances = buildStack ?? new Stack <Instance>();
        }
        public T Build <T>(TypeArguments arguments)
        {
            var explicitArguments = new ExplicitArguments();

            foreach (var pair in arguments.Defaults)
            {
                explicitArguments.Set(pair.Key, pair.Value);
            }

            return(Container.GetInstance <T>(explicitArguments));
        }
Exemple #34
0
        static ExplicitArguments CreateActivatorArguments(QueryMiddleware <TArgs, TResult> next, object[] args)
        {
            var expArgs = new ExplicitArguments();

            expArgs.Set(next);
            foreach (var arg in args)
            {
                expArgs.Set(arg.GetType(), arg);
            }
            return(expArgs);
        }
        public BuildUpTester()
        {
            theDefaultGateway = new DefaultGateway();

            var args = new ExplicitArguments();
            args.Set<IGateway>(theDefaultGateway);
            session = BuildSession.Empty(args);

            theDependencies = new DependencyCollection { { "Age", 34 } };

            target = null;
        }
        private static ExplicitArguments getExplicitArguments(bool isNamed, MethodInfo methodInfo, IList<object> arguments)
        {
            var explicitArguments = new ExplicitArguments();

            var parameters = methodInfo.GetParameters();

            for (var i = isNamed ? 1 : 0; i < arguments.Count; ++i)
            {
                explicitArguments.SetArg(parameters[i].Name, arguments[i]);
            }
            return explicitArguments;
        }
        public void RegisterAndRetrieveArgs()
        {
            var args = new ExplicitArguments();

            Assert.IsNull(args.GetArg("name"));

            args.SetArg("name", "Jeremy");
            Assert.AreEqual("Jeremy", args.GetArg("name"));

            args.SetArg("age", 34);
            Assert.AreEqual(34, args.GetArg("age"));
        }
Exemple #38
0
        public void SetUp()
        {
            TheDefaultGateway = new DefaultGateway();

            var args = new ExplicitArguments();
            args.Set<IGateway>(TheDefaultGateway);

            builder = new Plugin(typeof (ClassWithMixOfSetters)).CreateBuilder();
            instance = new SmartInstance<ClassWithMixOfSetters>().Ctor<int>("Age").Is(34);
            _session = BuildSession.Empty(args);

            _target = null;
        }
        public void SetUp()
        {
            TheDefaultGateway = new DefaultGateway();


            var args = new ExplicitArguments();
            args.Set<IGateway>(TheDefaultGateway);
            _session = BuildSession.Empty(args);

            theDependencies = new DependencyCollection {{"Age", 34}};


            _target = null;
        }
        public void Pass_in_arguments_as_dictionary()
        {
            ObjectFactory.Initialize(x => { x.ForRequestedType<IView>().TheDefaultIsConcreteType<View>(); });

            var theNode = new Node();
            var theTrade = new Trade();

            var args = new ExplicitArguments();
            args.Set(theNode);
            args.SetArg("trade", theTrade);

            var command = ObjectFactory.GetInstance<Command>(args);

            Assert.IsInstanceOfType(typeof (View), command.View);
            Assert.AreSame(theNode, command.Node);
            Assert.AreSame(theTrade, command.Trade);
        }
Exemple #41
0
        public void should_add_the_instance_name_when_created_with_type()
        {
            var container = new Container(_ =>
            {
                _.Policies.Interceptors(new DecoratorPolicy());

                _.For<IService>().MissingNamedInstanceIs.Type<FallbackService>();
            });

            var serviceName = "Bla";

            var arguments = new ExplicitArguments().Set(Guid.NewGuid());

            var decorator = container.GetInstance<IService>(arguments, serviceName) as DecoratorService;

            decorator.ShouldNotBeNull();
            decorator.Name.ShouldBe(serviceName);
            decorator.DecoratedService.ShouldBeOfType<FallbackService>();
        }
        public void explicit_wins_over_instance_in_try_get_default()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolverMock, args);

            var instance = new ConfiguredInstance(typeof(Foo));
            instanceGraphMock.GetDefault(typeof(IFoo)).Returns(instance);

            var foo2 = new Foo();

            theResolverMock.ResolveFromLifecycle(typeof(IFoo), instance).Returns(foo2);

            theCache.GetDefault(typeof(IFoo), thePipeline)
                .ShouldBeTheSameAs(foo1);
        }
        public void explicit_wins_over_instance_in_try_get_default()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            var instance = new ConfiguredInstance(typeof (Foo));
            theInstances.Stub(x => x.GetDefault(typeof (IFoo))).Return(instance);

            var foo2 = new Foo();

            theResolver.Expect(x => x.ResolveFromLifecycle(typeof (IFoo), instance)).Return(foo2)
                .Repeat.Once();

            theCache.GetDefault(typeof (IFoo), thePipeline)
                .ShouldBeTheSameAs(foo1);
        }
        public virtual IPresenter Create(Type presenterType, Type viewType, IView viewInstance)
        {
            Type abstractViewType = this.GetAbstractViewType(presenterType);

            if(viewType == null)
                throw new ArgumentNullException("viewType");

            if(!typeof(IView).IsAssignableFrom(viewType))
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The view-type \"{0}\" must implement \"{1}\".", viewType.FullName, typeof(IView).FullName), "viewType");

            if(viewInstance == null)
                throw new ArgumentNullException("viewInstance");

            ExplicitArguments explicitArguments = new ExplicitArguments();
            explicitArguments.Set(abstractViewType, viewInstance);

            IPresenter presenter = (IPresenter) this._container.GetInstance(presenterType, explicitArguments);

            if(presenter == null)
                throw new StructureMapException(202, new object[] {presenterType});

            return presenter;
        }
        public void RegisterAndRetrieveArgs()
        {
            var args = new ExplicitArguments();
            Assert.IsNull(args.GetArg("name"));

            args.SetArg("name", "Jeremy");
            Assert.AreEqual("Jeremy", args.GetArg("name"));

            args.SetArg("age", 34);
            Assert.AreEqual(34, args.GetArg("age"));
        }
        public void Pass_in_arguments_as_dictionary()
        {
            var container = new Container(x => { x.For<IView>().Use<View>(); });

            var theNode = new Node();
            var theTrade = new Trade();

            var args = new ExplicitArguments();
            args.Set(theNode);
            args.SetArg("trade", theTrade);

            var command = container.GetInstance<Command>(args);

            command.View.ShouldBeOfType<View>();
            theNode.ShouldBeTheSameAs(command.Node);
            theTrade.ShouldBeTheSameAs(command.Trade);
        }
        public void RegisterAndFindServicesOnTheExplicitArgument()
        {
            var args = new ExplicitArguments();
            Assert.IsNull(args.Get<IProvider>());

            var red = new RedProvider();
            args.Set<IProvider>(red);

            Assert.AreSame(red, args.Get<IProvider>());

            args.Set<IExplicitTarget>(new RedTarget());
            args.Get<IExplicitTarget>().ShouldBeOfType<RedTarget>();
        }
        public void PassAnArgumentIntoExplicitArgumentsForARequestedInterface()
        {
            IContainer manager =
                new Container(
                    registry => registry.For<IProvider>().Use<LumpProvider>());

            var args = new ExplicitArguments();
            var theLump = new Lump();
            args.Set(theLump);

            var instance = (LumpProvider) manager.GetInstance<IProvider>(args);
            Assert.AreSame(theLump, instance.Lump);
        }
        public void PassExplicitArgsIntoInstanceManager()
        {
            var container = new Container(r =>
            {
                r.ForConcreteType<ExplicitTarget>().Configure
                    .Ctor<IProvider>().Is<RedProvider>()
                    .Ctor<string>("name").Is("Jeremy");
            });

            var args = new ExplicitArguments();

            // Get the ExplicitTarget without setting an explicit arg for IProvider
            var firstTarget = container.GetInstance<ExplicitTarget>(args);
            firstTarget.Provider.ShouldBeOfType<RedProvider>();

            // Now, set the explicit arg for IProvider
            args.Set<IProvider>(new BlueProvider());
            var secondTarget = container.GetInstance<ExplicitTarget>(args);
            secondTarget.Provider.ShouldBeOfType<BlueProvider>();
        }
        public void get_instance_with_args()
        {
            var container = new Container(x =>
            {
                x.For<FakeLogger>().Use(c => new FakeLogger(c.RootType));

                x.For<ILoggerHolder>().Use<WidgetLoggerHolder>();
            });

            var explicitArguments = new ExplicitArguments();
            explicitArguments.Set<IWidget>(new AWidget());
            container.GetInstance<ILoggerHolder>(explicitArguments)
                .Logger.RootType.ShouldBe(typeof (WidgetLoggerHolder));
        }
        public void try_get_default_with_explicit_arg()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            theCache.GetDefault(typeof (IFoo), thePipeline)
                    .ShouldBeTheSameAs(foo1);
        }
 public NestedStructureMapContainerBehavior(IContainer container, ServiceArguments arguments, Guid behaviorId)
 {
     _container = container;
     _arguments = arguments.ToExplicitArgs();
     _behaviorId = behaviorId;
 }
		public IVersionControlSystem Get(ISourceControlConnectionSettingsSource settings)
		{
			var vcsArgs = new ExplicitArguments();
			vcsArgs.Set(settings);
			return ObjectFactory.GetInstance<IVersionControlSystem>(vcsArgs);
		}
        public void PassExplicitArgsIntoInstanceManager()
        {
            var container = new Container(r =>
            {
                r.ForConcreteType<ExplicitTarget>().Configure
                    .CtorDependency<IProvider>().Is<RedProvider>()
                    .WithCtorArg("name").EqualTo("Jeremy");
            });

            var args = new ExplicitArguments();

            // Get the ExplicitTarget without setting an explicit arg for IProvider
            var firstTarget = container.GetInstance<ExplicitTarget>(args);
            Assert.IsInstanceOfType(typeof (RedProvider), firstTarget.Provider);

            // Now, set the explicit arg for IProvider
            args.Set<IProvider>(new BlueProvider());
            var secondTarget = container.GetInstance<ExplicitTarget>(args);
            Assert.IsInstanceOfType(typeof (BlueProvider), secondTarget.Provider);
        }
        public void start_with_explicit_args()
        {
            var foo1 = new Foo();

            var args = new ExplicitArguments();
            args.Set<IFoo>(foo1);

            theCache = new SessionCache(theResolver, args);

            thePipeline.Stub(x => x.GetDefault(typeof (IFoo))).Throw(new NotImplementedException());

            theCache.GetDefault(typeof (IFoo), thePipeline)
                    .ShouldBeTheSameAs(foo1);
        }
        public static void Configure(IContainer container, JsonApiConfiguration jsonApiConfiguration)
        {
            container.Configure(cfg => cfg.AddRegistry<JsonApiRegistry>());

            var registry = new ResourceTypeRegistry();
            foreach (var resourceTypeConfiguration in jsonApiConfiguration.ResourceTypeConfigurations)
            {
                var resourceTypeRegistration = resourceTypeConfiguration.BuildResourceTypeRegistration();
                registry.AddRegistration(resourceTypeRegistration);

                var configuration = resourceTypeConfiguration;


                container.Configure(cfg =>
                {
                    cfg.For<IResourceTypeConfiguration>().Use(configuration).Named(resourceTypeRegistration.Type.FullName).Singleton();
                    cfg.For<IResourceTypeConfiguration>().Use(configuration).Named(resourceTypeRegistration.ResourceTypeName).Singleton();
                });

                if (resourceTypeConfiguration.DocumentMaterializerType != null)
                {
                    container.Configure(cfg => cfg.For(resourceTypeConfiguration.DocumentMaterializerType));
                }

                foreach (var relationship in resourceTypeRegistration.Relationships)
                {
                    IResourceTypeRelationshipConfiguration relationshipConfiguration;
                    if (resourceTypeConfiguration.RelationshipConfigurations
                        .TryGetValue(relationship.Property.Name, out relationshipConfiguration))
                    {
                        if (relationshipConfiguration.MaterializerType != null)
                        {
                            container.Configure(cfg => cfg.For(relationshipConfiguration.MaterializerType));
                            continue;
                        }
                    }

                    // They didn't set an explicit materializer. See if they specified a factory for this resource type.
                    if (configuration.RelatedResourceMaterializerTypeFactory == null) continue;

                    var materializerType = configuration.RelatedResourceMaterializerTypeFactory(relationship);
                    container.Configure(cfg => cfg.For(materializerType));
                }
            }
            container.Configure(cfg => cfg.For<IResourceTypeRegistry>().Use(c => registry).Singleton());


            container.Configure(cfg =>
            {
                cfg.For<IDocumentMaterializerLocator>()
                    .Use<DocumentMaterializerLocator>()
                    .Ctor<Func<string, IDocumentMaterializer>>().Is(resourceTypeName =>
                    {
                        var configuration = container.GetInstance<IResourceTypeConfiguration>(resourceTypeName);
                        var registration = registry.GetRegistrationForResourceTypeName(resourceTypeName);
                        var args = new ExplicitArguments();
                        args.Set<IResourceTypeRegistration>(registration);
                        if (configuration.DocumentMaterializerType != null)
                            return
                                (IDocumentMaterializer)
                                    container.With(args).GetInstance(configuration.DocumentMaterializerType);
                        return container.With(args).GetInstance<IDocumentMaterializer>();
                    })
                    .Ctor<Func<Type, IDocumentMaterializer>>().Is(type =>
                    {
                        var configuration = container.GetInstance<IResourceTypeConfiguration>(type.FullName);
                        var registration = registry.GetRegistrationForType(type);
                        var args = new ExplicitArguments();
                        args.Set<IResourceTypeRegistration>(registration);
                        if (configuration.DocumentMaterializerType != null)
                            return
                                (IDocumentMaterializer)
                                    container.With(args).GetInstance(configuration.DocumentMaterializerType);
                        return container.With(args).GetInstance<IDocumentMaterializer>();
                    })
                    .Ctor<Func<string, string, IRelatedResourceDocumentMaterializer>>().Is((resourceTypeName, relationshipName) =>
                    {
                        var configuration = container.GetInstance<IResourceTypeConfiguration>(resourceTypeName);
                        var registration = registry.GetRegistrationForResourceTypeName(resourceTypeName);
                        var relationship = registration.GetFieldByName(relationshipName) as ResourceTypeRelationship;
                        if (relationship == null)
                            throw JsonApiException.CreateForNotFound(
                                string.Format("No relationship `{0}` exists for the resource type `{1}`.", relationshipName, resourceTypeName));

                        var args = new ExplicitArguments();
                        args.Set<IResourceTypeRegistration>(registration);
                        args.Set<ResourceTypeRelationship>(relationship);

                        // First, see if they have set an explicit materializer for this relationship
                        IResourceTypeRelationshipConfiguration relationshipConfiguration;
                        if (configuration.RelationshipConfigurations.TryGetValue(relationship.Property.Name,
                            out relationshipConfiguration) && relationshipConfiguration.MaterializerType != null)
                            return (IRelatedResourceDocumentMaterializer)container.With(args).GetInstance(relationshipConfiguration.MaterializerType);

                        // They didn't set an explicit materializer. See if they specified a factory for this resource type.
                        if (configuration.RelatedResourceMaterializerTypeFactory != null)
                        {
                            var materializerType = configuration.RelatedResourceMaterializerTypeFactory(relationship);
                            return (IRelatedResourceDocumentMaterializer)container.With(args).GetInstance(materializerType);
                        }

                        return container.With(args).GetInstance<IRelatedResourceDocumentMaterializer>();
                    });
            });

            container.Configure(cfg => cfg.For<ILinkConventions>().Use(c => jsonApiConfiguration.LinkConventions).Singleton());


        }