Example #1
0
 public static T GetService <T>(string name, object obj)
 {
     return(ResolutionExtensions.Resolve <T>(AutofacManage.container, new Parameter[]
     {
         new NamedParameter(name, obj)
     }));
 }
Example #2
0
        private static void Main()
        {
            var conf = new Configuration(ExecutionEnvironment.Test);

            BootStrapDependencies(conf);
            HostFactory.Run(x =>
            {
                RunAsExtensions.RunAs(x, conf.ServiceUserName, conf.ServiceUserPasswordEncrypted);
                x.SetDescription("Calculates and provides calendar and product info data.");
                StartModeExtensions.StartManually(x);
                x.SetDisplayName(conf.ServiceDisplayName);
                x.SetServiceName(conf.ServiceName);
                ServiceExtensions.Service <PricingService>(x, s =>
                {
                    s.ConstructUsing(
                        name =>
                        new PricingService(ResolutionExtensions.Resolve <Configuration>(Container)));
                    ServiceConfiguratorExtensions.WhenStarted <PricingService>(s, tc => tc.OnStart());
                    ServiceConfiguratorExtensions.WhenStopped <PricingService>(s, tc => tc.OnStop());
                    ServiceConfiguratorExtensions.WhenShutdown <PricingService>(s, tc => tc.OnStop());
                });
                InstallHostConfiguratorExtensions.BeforeInstall(x, () => NetShellCmdLineTool.RegisterHttpNamespace(conf));
                UninstallHostConfiguratorExtensions.AfterUninstall(x, () => NetShellCmdLineTool.UnregisterHttpNamespace(conf));
            });
        }
Example #3
0
 protected sealed override IEnumerable <object> GetAllInstances(Type service)
 {
     return(ResolutionExtensions.Resolve(this.Container, typeof(IEnumerable <>).MakeGenericType(new Type[]
     {
         service
     })) as IEnumerable <object>);
 }
Example #4
0
        public static Registration <T> CreateRegistration <T>(RegistrationContext context, Func <ILifetimeScope, T> resolveWithLifetimeScopeFunc = null, Func <IOwinContext, T> resolveWithOwinContextFunc = null, string name = null) where T : class
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var mode = context.ConvertMode();

            if (mode == RegistrationMode.Singleton)
            {
                // ReSharper disable once PossibleNullReferenceException
                return new Registration <T>(ResolutionExtensions.Resolve <T>((IComponentContext)context.SingletonLifetimeScope), name)
                       {
                           Mode = RegistrationMode.Singleton
                       }
            }
            ;

            return(new Registration <T>(
                       dr => dr.ResolveUsingAutofac <T>(resolveWithLifetimeScopeFunc, resolveWithOwinContextFunc))
            {
                Mode = mode
            });
        }
Example #5
0
 /// <summary>
 /// Resolves all requested service instances.
 ///
 /// </summary>
 /// <param name="serviceType">Type of instance requested.</param>
 /// <returns>
 /// Sequence of service instance objects.
 /// </returns>
 /// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="serviceType"/> is <see langword="null"/>.
 ///             </exception>
 protected override IEnumerable <object> DoGetAllInstances(Type serviceType)
 {
     if (serviceType == null)
     {
         throw new ArgumentNullException("serviceType");
     }
     return(Enumerable.Cast <object>((IEnumerable)ResolutionExtensions.Resolve(this._container, typeof(IEnumerable <>).MakeGenericType(serviceType))));
 }
Example #6
0
 protected sealed override object GetInstance(Type service, string key)
 {
     if (key != null)
     {
         return(ResolutionExtensions.ResolveNamed(this.Container, key, service));
     }
     return(ResolutionExtensions.Resolve(this.Container, service));
 }
Example #7
0
        public override IEnumerable <object> GetServices(Type serviceType)
        {
            var enumServiceType = typeof(IEnumerable <>).MakeGenericType(new Type[] { serviceType });
            var instance        = ResolutionExtensions.Resolve(this.lifetimeScope, enumServiceType) as IEnumerable <object>;

            if (!instance.Any())
            {
                return(base.GetServices(serviceType));
            }
            return(instance);
        }
Example #8
0
 /// <summary>
 /// Resolves the requested service instance.
 ///
 /// </summary>
 /// <param name="serviceType">Type of instance requested.</param><param name="key">Name of registered service you want. May be <see langword="null"/>.</param>
 /// <returns>
 /// The requested service instance.
 /// </returns>
 /// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="serviceType"/> is <see langword="null"/>.
 ///             </exception>
 protected override object DoGetInstance(Type serviceType, string key)
 {
     if (serviceType == null)
     {
         throw new ArgumentNullException("serviceType");
     }
     if (key == null)
     {
         return(ResolutionExtensions.Resolve(this._container, serviceType));
     }
     return(ResolutionExtensions.ResolveNamed(this._container, key, serviceType));
 }
Example #9
0
        private ISolrCoreAdmin BuildCoreAdmin()
        {
            SolrConnection solrConnection = new SolrConnection(SolrContentSearchManager.ServiceAddress);
            int            timeout;

            int.TryParse(Settings.GetSetting("SolrConnectionTimeout", "200000"), out timeout);
            solrConnection.Timeout = timeout;
            if (SolrContentSearchManager.EnableHttpCache)
            {
                solrConnection.Cache = ResolutionExtensions.Resolve <ISolrCache>((IComponentContext)this.container) ?? (ISolrCache) new NullCache();
            }
            return((ISolrCoreAdmin) new SolrCoreAdmin((ISolrConnection)solrConnection, ResolutionExtensions.Resolve <ISolrHeaderResponseParser>((IComponentContext)this.container), ResolutionExtensions.Resolve <ISolrStatusResponseParser>((IComponentContext)this.container)));
        }
Example #10
0
        /// <summary>
        /// 获取InstancePerHttpRequest的组件
        /// </summary>
        /// <typeparam name="TService">组件类型</typeparam>
        /// <returns></returns>
        public static TService ResolvePerHttpRequest <TService>()
        {
            IDependencyResolver current = DependencyResolver.Current;

            if (current != null)
            {
                TService service = (TService)current.GetService(typeof(TService));
                if (service != null)
                {
                    return(service);
                }
            }
            return(ResolutionExtensions.Resolve <TService>(_container));
        }
Example #11
0
        public static void Initialize()
        {
            var containerBuilder = new ContainerBuilder();

            RegistrationExtensions.RegisterType <TaskEvaluator>(containerBuilder);
            RegistrationExtensions.RegisterType <TaskTimer>(containerBuilder);
            var directoryCatalog = new DirectoryCatalog(Environment.CurrentDirectory);

            RegistrationExtensions.RegisterComposablePartCatalog(containerBuilder, (ComposablePartCatalog)directoryCatalog, new Service[1]
            {
                (Service) new TypedService(typeof(ITask))
            });
            ((IRegistrationBuilder <IEnumerable <TaskInfo>, SimpleActivatorData, SingleRegistrationStyle>)RegistrationExtensions.Register <IEnumerable <TaskInfo> >(containerBuilder, (Func <IComponentContext, M0>)(c => Enumerable.Select <Export, TaskInfo>(RegistrationExtensions.ResolveExports <ITask>((IComponentContext)ResolutionExtensions.Resolve <IComponentContext>(c)), (Func <Export, TaskInfo>)(e => new TaskInfo(TimeSpan.FromMilliseconds((double)(int)e.Metadata["MinInterval"]), (string)e.Metadata["Name"], (Func <ITask>)(() => (ITask)e.Value))))))).As <IEnumerable <TaskInfo> >();
            using (IContainer icontainer = containerBuilder.Build((ContainerBuildOptions)0))
                ((TaskTimer)ResolutionExtensions.Resolve <TaskTimer>((IComponentContext)icontainer)).Run();
        }
Example #12
0
        public static void Initialize()
        {
            ContainerBuilder builder = new ContainerBuilder();

            Autofac.RegistrationExtensions.RegisterType <TaskEvaluator>(builder);
            Autofac.RegistrationExtensions.RegisterType <TaskTimer>(builder);
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(Environment.CurrentDirectory);

            Autofac.Integration.Mef.RegistrationExtensions.RegisterComposablePartCatalog(builder, (ComposablePartCatalog)directoryCatalog, new Service[1]
            {
                (Service) new TypedService((Type)typeof(ITask))
            });
            Autofac.RegistrationExtensions.Register <IEnumerable <TaskInfo> >(builder, (Func <IComponentContext, IEnumerable <TaskInfo> >)(c => Enumerable.Select <Export, TaskInfo>(Autofac.Integration.Mef.RegistrationExtensions.ResolveExports <ITask>(ResolutionExtensions.Resolve <IComponentContext>(c)), (Func <Export, TaskInfo>)(e => new TaskInfo(TimeSpan.FromMilliseconds((double)(int)e.Metadata["MinInterval"]), (string)e.Metadata["Name"], (Func <ITask>)(() => (ITask)e.Value)))))).As <IEnumerable <TaskInfo> >();
            using (IContainer container = builder.Build(ContainerBuildOptions.None))
                ResolutionExtensions.Resolve <TaskTimer>((IComponentContext)container).Run();
        }
Example #13
0
        public static T GetService <T>(IDictionary <string, object> dict)
        {
            if (dict == null || dict.Count == 0)
            {
                return(AutofacManage.GetService <T>());
            }
            NamedParameter[] array = new NamedParameter[dict.Count];
            int num = 0;

            foreach (KeyValuePair <string, object> current in dict)
            {
                array[num++] = new NamedParameter(current.Key, current.Value);
            }
            IComponentContext _contain = AutofacManage.container;

            Parameter[] paramer = array;
            return(ResolutionExtensions.Resolve <T>(_contain, paramer));
        }
        public static Registration <T> CreateRegistration <T>(Func <ILifetimeScope, T> resolveWithLifetimeScopeFunc = null, Func <IOwinContext, T> resolveWithOwinContextFunc = null, string name = null, IContainer container = null, RegistrationContext context = null, bool checkForMiddleware = true) where T : class
        {
            var mode = context?.ConvertMode() ?? RegistrationMode.InstancePerUse; // play it safe with InstancePerUse

            if (mode == RegistrationMode.Singleton)
            {
                // ReSharper disable once PossibleNullReferenceException
                return new Registration <T>(ResolutionExtensions.Resolve <T>((IComponentContext)context.SingletonLifetimeScope), name)
                       {
                           Mode = RegistrationMode.Singleton
                       }
            }
            ;

            return(new Registration <T>(
                       dr => dr.ResolveUsingAutofac <T>(resolveWithLifetimeScopeFunc, resolveWithOwinContextFunc, container ?? context?.Container, checkForMiddleware))
            {
                Mode = mode
            });
        }
        private static void OnComponentActivated(object sender, ActivatedEventArgs <object> args)
        {
            if (args == null)
            {
                return;
            }
            IHandle handler;

            if ((handler = (args.get_Instance() as IHandle)) == null)
            {
                return;
            }
            ILifetimeScope   lifetimeScope   = ResolutionExtensions.Resolve <ILifetimeScope>(args.get_Context());
            IEventAggregator eventAggregator = ResolutionExtensions.Resolve <IEventAggregator>(lifetimeScope);

            eventAggregator.Subscribe(handler);
            EventAggregationAutoSubscriptionModule.DisposableAction disposableAction = new EventAggregationAutoSubscriptionModule.DisposableAction(delegate
            {
                eventAggregator.Unsubscribe(handler);
            });
            lifetimeScope.get_Disposer().AddInstanceForDisposal(disposableAction);
        }
Example #16
0
 protected override void Load(ContainerBuilder builder)
 {
     RegistrationExtensions.Register(builder, c => new CustomWebDownloader()).As <IWebDownloader>().ExternallyOwned();
     RegistrationExtensions.Register(builder, c => new HashtagIndependentInMemoryCrawlerHistoryService()).As <ICrawlerHistory>().InstancePerDependency();
     RegistrationExtensions.Register(builder, c => new InMemoryCrawlerQueueService()).As <ICrawlerQueue>().InstancePerDependency();
     RegistrationExtensions.Register(builder, c => new LogLoggerBridge(CreateLogger())).As <ILog>().InstancePerDependency();
     RegistrationExtensions.Register(builder, c => new NativeTaskRunnerService()).As <ITaskRunner>().InstancePerDependency();
     RegistrationExtensions.Register(builder, (c, p) => new RobotService(ParameterExtensions.TypedAs <IEnumerable <Uri> >(p), ResolutionExtensions.Resolve <IWebDownloader>(c))).As <IRobot>().InstancePerDependency();
     RegistrationExtensions.Register(builder, (c, p) => new CrawlerRulesService(ParameterExtensions.TypedAs <Crawler>(p), ResolutionExtensions.Resolve <IRobot>(c, p), ParameterExtensions.TypedAs <IEnumerable <Uri> >(p))).As <ICrawlerRules>().InstancePerDependency();
 }
Example #17
0
 private static T ResolveAllWithParameters <T>(IEnumerable <Parameter> parameters)
 {
     return(ResolutionExtensions.Resolve <T>(ServiceLocator._container, parameters));
 }
Example #18
0
 protected T Resolve <T>()
 {
     return(ResolutionExtensions.Resolve <T>(this.Container));
 }
Example #19
0
 public static object GetInstance(Type serviceType)
 {
     ServiceLocator.CheckReady();
     return(ResolutionExtensions.Resolve(ServiceLocator._container, serviceType));
 }
Example #20
0
 public static T GetService <T>()
 {
     return(ResolutionExtensions.Resolve <T>(AutofacManage.container));
 }
Example #21
0
 /// <summary>
 /// 按参数获取组件
 /// </summary>
 /// <typeparam name="TService">组件类型</typeparam>
 /// <returns>返回获取的组件</returns>
 public static TService Resolve <TService>()
 {
     return(ResolutionExtensions.Resolve <TService>(_container));
 }
Example #22
0
        public void Initialize()
        {
            if (!SolrContentSearchManager.IsEnabled)
            {
                throw new InvalidOperationException("Solr configuration is not enabled. Please check your settings and include files.");
            }
            foreach (string coreId in SolrContentSearchManager.Cores)
            {
                this.AddCore(coreId, typeof(Dictionary <string, object>), string.Format("{0}/{1}", (object)SolrContentSearchManager.ServiceAddress, (object)coreId));
            }

            builder.RegisterModule((IModule) new SolrNetModule(this.Cores));
            RegistrationExtensions.RegisterType <SolrFieldBoostingDictionarySerializer>(this.builder).As <ISolrDocumentSerializer <Dictionary <string, object> > >();
            if (SolrContentSearchManager.EnableHttpCache)
            {
                RegistrationExtensions.RegisterType <HttpRuntimeCache>(this.builder).As <ISolrCache>();
                foreach (SolrServerElement solrServerElement in (ConfigurationElementCollection)this.Cores)
                {
                    ((IRegistrationBuilder <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>)RegistrationExtensions.WithParameters <object, ConcreteReflectionActivatorData, SingleRegistrationStyle>(RegistrationExtensions.RegisterType(this.builder, typeof(SolrConnection)).Named(solrServerElement.Id + (object)typeof(SolrConnection), typeof(ISolrConnection)), (IEnumerable <Parameter>) new NamedParameter[1]
                    {
                        new NamedParameter("serverURL", (object)solrServerElement.Url)
                    })).OnActivated((Action <IActivatedEventArgs <object> >)(args => ((SolrConnection)args.Instance).Cache = ResolutionExtensions.Resolve <ISolrCache>(args.Context)));
                }
            }
            this.container = this.builder.Build(ContainerBuildOptions.None);
            ServiceLocator.SetLocatorProvider((ServiceLocatorProvider)(() => (IServiceLocator) new AutofacServiceLocator((IComponentContext)this.container)));
            SolrContentSearchManager.SolrAdmin = this.BuildCoreAdmin();
            SolrContentSearchManager.Initialize();
        }
Example #23
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TService">组件类型</typeparam>
 /// <param name="parameters">Autofac.Core.Parameter</param>
 /// <returns>返回获取的组件</returns>
 public static TService Resolve <TService>(params Parameter[] parameters)
 {
     return(ResolutionExtensions.Resolve <TService>(_container, parameters));
 }
Example #24
0
 public static T GetInstance <T>(params object[] prms)
 {
     ServiceLocator.CheckReady();
     return(ResolutionExtensions.Resolve <T>(ServiceLocator._container, from p in prms
                                             select new TypedParameter(p.GetType(), p)));
 }
 public T Resolve <T>()
 {
     ResolutionExtensions.Resolve <T>(AutofacContainer);
     return(ResolutionExtensions.Resolve <T>(AutofacContainer));
 }
 internal IVpnServiceManager <Load> b__0_0(IComponentContext ctx, IVpnServiceManager inner)
 {
     return(new VpnServiceManagerLoggingDecorator(inner, ResolutionExtensions.Resolve <ILogger>(ctx)));
 }
Example #27
0
 public static T GetInstance <T>()
 {
     ServiceLocator.CheckReady();
     return(ResolutionExtensions.Resolve <T>(ServiceLocator._container));
 }