コード例 #1
0
 public void AddDependencyInjectionBehavior_NullContractType_ThrowsException()
 {
     ServiceHost serviceHost = new ServiceHost(typeof(ServiceType));
     ArgumentNullException exception = Assert.Throws<ArgumentNullException>(
         () => serviceHost.AddDependencyInjectionBehavior(null, new ContainerBuilder().Build()));
     Assert.That(exception.ParamName, Is.EqualTo("contractType"));
 }
コード例 #2
0
 public void AddDependencyInjectionBehavior_NullContainer_ThrowsException()
 {
     ServiceHost serviceHost = new ServiceHost(typeof(ServiceType));
     ArgumentNullException exception = Assert.Throws<ArgumentNullException>(
         () => serviceHost.AddDependencyInjectionBehavior(typeof(IContractType), null));
     Assert.Equal("container", exception.ParamName);
 }
コード例 #3
0
        public void Start()
        {
            //SchedulerService
            var schedulerServiceHost = new ServiceHost(typeof(SchedulerService), 
                new Uri("net.pipe://localhost/SchedulerService"));
            schedulerServiceHost.AddServiceEndpoint(typeof(ISchedulerService), new NetNamedPipeBinding(), string.Empty);
            schedulerServiceHost.AddDependencyInjectionBehavior<ISchedulerService>(container);
            hosts.Add(schedulerServiceHost);

            //BoxQueryService
            var boxQueryService = new ServiceHost(typeof(BoxQueryService),
                new Uri("net.pipe://localhost/BoxQueryService"));
            boxQueryService.AddServiceEndpoint(typeof(IBoxQueryService), new NetNamedPipeBinding(), string.Empty);
            boxQueryService.AddDependencyInjectionBehavior<IBoxQueryService>(container);
            hosts.Add(boxQueryService);
            
            //BoxQueryService
            var commonsService = new ServiceHost(typeof(CommonsService),
                new Uri("net.pipe://localhost/CommonsService"));
            commonsService.AddServiceEndpoint(typeof(ICommonsService), new NetNamedPipeBinding(), string.Empty);
            commonsService.AddDependencyInjectionBehavior<ICommonsService>(container);
            hosts.Add(commonsService);

            //StateBrowsingService
            var stateService = new ServiceHost(typeof(StateBrowsingService),
                new Uri("net.pipe://localhost/StateBrowsingService"));
            stateService.AddServiceEndpoint(typeof(IStateBrowsingService), new NetNamedPipeBinding(), string.Empty);
            stateService.AddDependencyInjectionBehavior<IStateBrowsingService>(container);
            hosts.Add(stateService);

            hosts.ForEach(host => host.Open());
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: skohub/CarControl
        static void Main(string[] args)
        {
            var builder = AutofacConfig.ConfigureContainer();
            using (var container = builder.Build())
            {
                // Car commands
                var carProtoServer = container.Resolve<ICarProtoServer>();
                carProtoServer.GetInputCommandFactory = () =>
                {
                    var scope = container.BeginLifetimeScope();
                    carProtoServer.OnClientDisconnected = () => scope.Dispose();
                    return scope.Resolve<ICommandFactory>();
                };

                // Wcf
                var address = new Uri("http://localhost:4998");
                var host = new ServiceHost(typeof(CarCommand), address);
                host.AddServiceEndpoint(typeof(ICarCommand), new WSDualHttpBinding(), string.Empty);
                host.AddDependencyInjectionBehavior<CarCommand>(container);
                host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address });
                host.Open();

                Console.WriteLine("Service running");
                Console.ReadLine();

                host.Close();
                Environment.Exit(0);
            }
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: tleviathan/DeepDiveIntoDI
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterType<DependencyComponent>().As<IDependency>();
            builder.RegisterType<SampleService>();

            Container = builder.Build();

            ServiceHost host = new ServiceHost(typeof(SampleService));

            host.AddDependencyInjectionBehavior(typeof(SampleService), Container);

            host.Open();

            Console.WriteLine("Service is running. Press 'Enter' to call operation.");
            Console.ReadLine();
            Console.WriteLine();

            ChannelFactory<ISampleService> channelFactory = new ChannelFactory<ISampleService>("");
            ISampleService proxy = channelFactory.CreateChannel();

            proxy.PerformOperation();

            Console.WriteLine();
            Console.WriteLine("Press 'Enter' to end.");
            Console.ReadLine();
        }
コード例 #6
0
        private void Run()
        {
            Console.WriteLine("Run a ServiceHost via administrative configuration...");
            Console.WriteLine();

            using (ServiceHost serviceHost = new ServiceHost(typeof(SalesService)))
            {
                serviceHost.AddDependencyInjectionBehavior<ISalesService>(AutofacHostFactory.Container);

                Console.WriteLine("Opening the host");
                serviceHost.Open();

                try
                {
                    AutofacHostFactory.Container.Resolve<ISalesService>();
                    Console.WriteLine("The service is ready.");
                    Console.WriteLine("Press <ENTER> to terminate service.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error on initializing the service host.");
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine();
                Console.ReadLine();
                serviceHost.Close();
            }
        }
コード例 #7
0
 public void AddDependencyInjectionBehavior_ContractTypeNotRegistered_ThrowsException()
 {
     ServiceHost serviceHost = new ServiceHost(typeof(ServiceType));
     Type contractType = typeof(IContractType);
     ArgumentException exception = Assert.Throws<ArgumentException>(
         () => serviceHost.AddDependencyInjectionBehavior(contractType, new ContainerBuilder().Build()));
     Assert.Equal("contractType", exception.ParamName);
     string message = string.Format(ServiceHostExtensionsResources.ContractTypeNotRegistered, contractType.FullName);
     Assert.Contains(message, exception.Message);
 }
コード例 #8
0
        public void Run()
        {
            var address = new Uri("http://localhost:8181/contact");
            host = new ServiceHost(typeof(ContactNotificationService), address);
            host.AddServiceEndpoint(typeof(NotificationPort), new BasicHttpBinding(), string.Empty);
            host.AddDependencyInjectionBehavior<ContactNotificationService>(EndpointConfig.Container); // Autofac extension
            host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address });

            Log.Info("Starting");
            host.Open();
            Log.Info("Started");
        }
コード例 #9
0
ファイル: App.xaml.cs プロジェクト: XMotoGodX/novaroma
        private async void App_OnStartup(object sender, StartupEventArgs e) {
            var client = Novaroma.Helper.CreateShellServiceClient();
            bool createdNew;
            try {
                client.Test();
                createdNew = false;
            }
            catch {
                createdNew = true;
            }

            if (!createdNew) {
                if (e.Args.Length > 0)
                    await client.HandleExeArgs(e.Args);
                else
                    await client.ShowMainWindow();

                Current.Shutdown();
                return;
            }

            IoCContainer.Build();

            var engine = IoCContainer.Resolve<INovaromaEngine>();
            engine.LanguageChanged += EngineOnLanguageChanged;

            _shellServiceHost = new ServiceHost(typeof(ShellService), new Uri(Constants.NetPipeUri));
            var shellBinding = new NetNamedPipeBinding {
                MaxReceivedMessageSize = 20000000,
                MaxBufferPoolSize = 20000000,
                MaxBufferSize = 20000000
            };
            _shellServiceHost.AddServiceEndpoint(typeof(IShellService), shellBinding, Constants.NetPipeEndpointName);
            _shellServiceHost.AddDependencyInjectionBehavior<IShellService>(IoCContainer.BaseContainer);
            _shellServiceHost.Open();

            var mainWindow = IoCContainer.Resolve<MainWindow>();
            var mainViewModel = IoCContainer.Resolve<MainViewModel>();
            await mainViewModel.ListData();
            if (!e.Args.Contains("StartHidden"))
                mainWindow.Show();

            _notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
            if (_notifyIcon != null)
                _notifyIcon.DataContext = IoCContainer.Resolve<NotifyIconViewModel>();

            if (e.Args.Length > 0) {
                var service = IoCContainer.Resolve<IShellService>();
                await service.HandleExeArgs(e.Args);
            }
        }
コード例 #10
0
        public void AddDependencyInjectionBehavior_ContractTypeRegistered_ServiceBehaviorConfigured()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new ServiceType()).As<IContractType>();
            IContainer container = builder.Build();

            ServiceHost serviceHost = new ServiceHost(typeof(ServiceType));
            serviceHost.AddDependencyInjectionBehavior(typeof(IContractType), container);

            int serviceBehaviorCount = serviceHost.Description.Behaviors
                .OfType<AutofacDependencyInjectionServiceBehavior>()
                .Count();
            Assert.Equal(1, serviceBehaviorCount);
        }
コード例 #11
0
ファイル: Bootstrap.cs プロジェクト: em881g/GitHelper
 public static void Load()
 {
     AutoMapperConfig.Configure(typeof(Core.Bootstrapper.Bootstrap).Assembly, typeof(Bootstrap).Assembly);
     AppDomain.CurrentDomain.SetData("DataDirectory","D:\\");
     var builder = new ContainerBuilder();
     builder.RegisterType<ProjectContext>().AsSelf().SingleInstance();
     builder.RegisterType<FileProviderImpl>().As<IFileProvider>().SingleInstance();
     builder.RegisterType<ProjectProvider>().As<IProjectProvider>().SingleInstance();
     builder.RegisterType<RepositoryProvider>().As<IRepoProvider>().SingleInstance();
     builder.RegisterType<GitHelperSrv>().As<IGitHelperSrv>().InstancePerLifetimeScope();
     Container = builder.Build();
     Host = new ServiceHost(typeof (GitHelperSrv));
     Host.AddDependencyInjectionBehavior<IGitHelperSrv>(Container);
     Host.Open();
     Core.Bootstrapper.Bootstrap.CheckProjects(Container);
 }
コード例 #12
0
        static void Main(string[] args)
        {
            var loader = new MacroMoney.Boostrapper.Loader();

            loader.Load();

            Console.WriteLine("Starting up services...");
            Console.WriteLine("");

            SM.ServiceHost hostAccountManager = new SM.ServiceHost(typeof(AccountManager));
            hostAccountManager.AddDependencyInjectionBehavior <IAccountService>(IoC.Container);

            SM.ServiceHost hostTransactionmanager = new SM.ServiceHost(typeof(TransactionManager));
            hostTransactionmanager.AddDependencyInjectionBehavior <ITransactionService>(IoC.Container);

            SM.ServiceHost hostUserManager = new SM.ServiceHost(typeof(UserManager));
            hostUserManager.AddDependencyInjectionBehavior <IUserService>(IoC.Container);

            SM.ServiceHost hostCategoryManager = new SM.ServiceHost(typeof(CategoryManager));
            hostCategoryManager.AddDependencyInjectionBehavior <ICategoryService>(IoC.Container);

            StartService(hostAccountManager, "AccountManager");
            StartService(hostTransactionmanager, "TransactionManager");
            StartService(hostUserManager, "UserManager");
            StartService(hostCategoryManager, "CategoryManager");

            //System.Timers.Timer timer = new System.Timers.Timer(10000);
            //timer.Elapsed += OnTimerElapsed;
            //timer.Start();

            //Console.WriteLine("Reservation monitor started.");

            Console.WriteLine("");
            Console.WriteLine("Press [Enter] to exit.");
            Console.ReadLine();
            Console.WriteLine("");

            //timer.Stop();

            //Console.WriteLine("Reservaton mointor stopped.");

            StopService(hostAccountManager, "AccountManager");
            StopService(hostTransactionmanager, "TransactionManager");
            StopService(hostUserManager, "UserManager");
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: omockler/Substrate
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new EntitiesModule());
            builder.RegisterModule(new ServicesModule());

            var serviceInformationList =
                new[]
                    {
                        new
                            {
                                Address = "UserRepositoryService",
                                InterfaceType = typeof (IUserRepositoryService),
                                ImplementationType = typeof (UserRepositoryService)
                            }
                    };

            using (var container = builder.Build())
            {
                var serviceHosts = new List<ServiceHost>(serviceInformationList.Length);
                foreach (var serviceInfo in serviceInformationList)
                {
                    var serviceUri = new Uri(ROOT_URI + serviceInfo.Address);
                    var serviceHost = new ServiceHost(serviceInfo.ImplementationType, serviceUri);
                    var debugBehavior = serviceHost.Description.Behaviors.Single(x => x is ServiceDebugBehavior) as ServiceDebugBehavior;
                    debugBehavior.IncludeExceptionDetailInFaults = true;
                    serviceHost.AddServiceEndpoint(serviceInfo.InterfaceType, new NetTcpBinding(), string.Empty);
                    serviceHost.AddDependencyInjectionBehavior(serviceInfo.InterfaceType, container);
                    serviceHost.Open();
                    serviceHosts.Add(serviceHost);
                    Console.WriteLine("Hosted service of type {0} at endpoint {1}", serviceInfo.InterfaceType, serviceUri);
                }

                Console.WriteLine("The host has been opened.");
                Console.ReadLine();

                foreach (var serviceHost in serviceHosts)
                {
                    serviceHost.Close();
                }

                Environment.Exit(0);
            }
        }
コード例 #14
0
        private void btnStartService_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _host = new ServiceHost(typeof(BlogPostController));
                _host.AddDependencyInjectionBehavior<IBlogPostService>(container);

                _host.Open();

                this.btnStopService.IsEnabled = true;
                this.btnStartService.IsEnabled = false;
                this.lblStatus.Content = "Service is running..";
                this.lblStatus.Foreground = new SolidColorBrush(Colors.RoyalBlue);
            }
            catch (Exception ex)
            {
                container.Dispose();
                MessageBox.Show(ex.Message);
            }
        }
コード例 #15
0
        public void Setup()
        {
            try
            {
                container = Bootstrapper.BuildContainer();

                svcArticleHost = new ServiceHost(typeof(ArticleService), svcArticleServiceURI);
                svcBlogHost = new ServiceHost(typeof(BlogService), svcBlogServiceURI);

                svcArticleHost.AddDependencyInjectionBehavior<Business.Services.Contracts.IArticleService>(container);
                svcBlogHost.AddDependencyInjectionBehavior<Business.Services.Contracts.IBlogService>(container);

                svcArticleHost.Open();
                svcBlogHost.Open();
            }
            catch (Exception ex)
            {
                svcArticleHost = null;
                svcBlogHost = null;
            }
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: GulinSS/LargePrimes-Sample
        static void Main(string[] args)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new WorkerPoolImpl()).AsImplementedInterfaces().SingleInstance();
            builder.Register(c => new NodeServiceImpl(c.Resolve<WorkerPool>())).As<NodeService>();
            builder.RegisterType<PrimeCalculatorImpl>().AsImplementedInterfaces();
            builder.RegisterType<SeederImpl>().AsImplementedInterfaces();

            using (IContainer container = builder.Build())
            {
                Uri address = new Uri(ConfigurationManager.AppSettings["host"]);
                ServiceHost host = new ServiceHost(typeof(NodeServiceImpl), address);

                host.AddServiceEndpoint(typeof(NodeService),
                    new WSDualHttpBinding(WSDualHttpSecurityMode.None)
                        {
                            SendTimeout = new TimeSpan(0, 0, 10),
                            ReceiveTimeout = new TimeSpan(0, 0, 10),
                            MaxBufferPoolSize = 1024 * 1024 * 1,
                            MaxReceivedMessageSize = 1024 * 1024 * 20,
                            MessageEncoding = WSMessageEncoding.Mtom,
                            ReaderQuotas =
                                new XmlDictionaryReaderQuotas
                                {
                                    MaxArrayLength = 1000000,
                                }
                        }, string.Empty);
                host.AddDependencyInjectionBehavior<NodeService>(container);
                host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address });
                host.Open();

                var calc = container.Resolve<PrimeCalculator>();
                WriteFile(calc.Calc(GetTaskFromInFile()));

                host.Close();
                Environment.Exit(0);
            }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: akesy/HR-Contracts-Module
        static void Main(string[] args)
        {
            AutoMapperConfig.RegisterMappings();

            var builder = new ContainerBuilder();
            builder.RegisterAssemblyModules(AppDomain.CurrentDomain.GetAssemblies());

            using (var container = builder.Build())
            {
                using (var host = new ServiceHost(typeof(ContractService)))
                {
                    var binding = new BasicHttpBinding();
                    host.AddServiceEndpoint(typeof(IContractService), binding, string.Empty);
                    host.AddServiceEndpoint(typeof(ISalaryService), binding, string.Empty);
                    host.AddDependencyInjectionBehavior<ContractService>(container);

                    host.Open();

                    Console.WriteLine("Host started @ " + DateTime.Now);
                    Console.ReadLine();
                }
            }
        }
コード例 #18
0
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<PluginService>();
            builder.Register<IPluginServiceHost>(c =>
            {
                var scope = c.Resolve<ILifetimeScope>();
                var cfg = c.Resolve<IConfiguration>();
                var uri = new Uri(string.Format(cfg.PluginUrlTemplate, "core"));

                var binding = new NetHttpBinding
                {
                    HostNameComparisonMode = HostNameComparisonMode.Exact,
                    MaxBufferPoolSize = 10485760,
                    MaxReceivedMessageSize = 10485760,
                };

                var host = new ServiceHost(typeof(PluginService));
                host.AddServiceEndpoint(typeof(IPluginService), binding, uri);
                host.AddDependencyInjectionBehavior(typeof(PluginService), scope);

                return new PluginServiceHost(host);
            });
        }
コード例 #19
0
        public void AddDependencyInjectionBehaviorWithGenericArgument_ContractTypeRegistered_ServiceBehaviorConfigured()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new ServiceType()).As<IContractType>();
            IContainer container = builder.Build();

            ServiceHost serviceHost = new ServiceHost(typeof(ServiceType));
            serviceHost.AddDependencyInjectionBehavior<IContractType>(container);

            int serviceBehaviorCount = serviceHost.Description.Behaviors
                .OfType<AutofacDependencyInjectionServiceBehavior>()
                .Count();
            Assert.That(serviceBehaviorCount, Is.EqualTo(1));
        }
コード例 #20
0
        public void Start()
        {
            var services = _knownServices.ToArray();
            Log.InfoFormat("Запуск WCF-хоста для {0} сервисов", services.Length);
            var hostName = _config.GetAppSettingString("Zen/Hostname");
            if (string.IsNullOrEmpty(hostName)) hostName = "localhost";

            var port = _config.GetAppSettingString("Zen/Port");
            if (string.IsNullOrEmpty(port)) port = "8080"; 
            
            foreach (var knownService in services)
            {
                Log.DebugFormat("Запуск хостов для типа: {0}", knownService.GetType().Name);
                IWebService service = knownService;
                var scope = AppScope.BeginScope(b => b.Register(ctx => this).As<WebserviceHostApplication>());
                _hostScopes.Add(scope);
                _hostThreads.Add(new Thread(() =>
                    {
                        var uriStr = string.Format("http://{0}:{1}/{2}", hostName, port, service.GetWebserviceName());
                        Uri address = new Uri(uriStr);

                        foreach (
                            var webService in
                                service.GetType()
                                       .GetInterfaces()
                                       .Where(i =>
                                              i.GetCustomAttributes(typeof (ServiceContractAttribute), true).Any() 
                                              && i != typeof (IWebService)))
                        {
                            try
                            {
                                Log.DebugFormat("Запуск хостов для типа: {0} по контракту {1}", service.GetType().Name,
                                                webService.Name);
                                ServiceHost host = new ServiceHost(service.GetType(), address);
                                host.AddServiceEndpoint(webService, new BasicHttpBinding(), string.Empty);

                                host.AddDependencyInjectionBehavior(webService, scope.Scope);

                                host.Description.Behaviors.Add(new ServiceMetadataBehavior
                                    {
                                        HttpGetEnabled = true,
                                        HttpGetUrl = address
                                    });
                                _hosts.Add(host);
                                host.Open();
                                var sb = new StringBuilder();
                                foreach (var ep in host.Description.Endpoints)
                                {
                                    sb.AppendFormat(
                                        "Для контракта: {1} сервиса {2} производится прослушивание по адресу {0}",
                                        ep.Address.Uri.AbsoluteUri,
                                        ep.Contract.Name,
                                        service.GetType().Name)
                                      .AppendLine();
                                }
                                Log.Info(sb.ToString());

                                var enumService = scope.Resolve<EnumeratorWebservice>();
                                if (enumService != null) enumService.RegisterService(service);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(string.Format("Ошибка инициализации веб-сервиса {1}:{0}", webService.Name,
                                                        service.GetType().Name), ex);
                            }
                        }
                    }));
            }

            foreach (var hostThread in _hostThreads)
            {
                hostThread.Start();
            }
        }
コード例 #21
0
        private void Run()
        {
            Console.WriteLine("Run a ServiceHost via programmatic configuration...");
            Console.WriteLine();

            string baseAddress = "http://" + Environment.MachineName + ":8000/Service.svc";
            Console.WriteLine("BaseAddress: {0}", baseAddress);

            using (ServiceHost serviceHost = new ServiceHost(typeof(SalesService), new Uri(baseAddress)))
            {
                WebHttpBinding webBinding = new WebHttpBinding
                {
                    ContentTypeMapper = new RawContentMapper(),
                    MaxReceivedMessageSize = 4194304,
                    MaxBufferSize = 4194304
                };

                serviceHost.AddServiceEndpoint(typeof(ISalesService), webBinding, "json")
                    .Behaviors.Add(new WebHttpJsonNetBehavior());

                //serviceHost.AddServiceEndpoint(typeof(ISalesService), new BasicHttpBinding(), baseAddress);
                serviceHost.AddDependencyInjectionBehavior<ISalesService>(AutofacHostFactory.Container);

                Console.WriteLine("Opening the host");
                serviceHost.Open();

                try
                {
                    AutofacHostFactory.Container.Resolve<ISalesService>();
                    Console.WriteLine("The service is ready.");
                    Console.WriteLine("Press <ENTER> to terminate service.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error on initializing the service host.");
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine();
                Console.ReadLine();

                serviceHost.Close();
            }
        }
コード例 #22
0
        public void AddDependencyInjectionBehavior_SingleInstanceContextMode_ServiceBehaviorIgnored()
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.Register(c => new SingletonServiceType()).As<IContractType>();
            IContainer container = builder.Build();

            ServiceHost serviceHost = new ServiceHost(typeof(SingletonServiceType));
            serviceHost.AddDependencyInjectionBehavior(typeof(IContractType), container);

            int serviceBehaviorCount = serviceHost.Description.Behaviors
                .OfType<AutofacDependencyInjectionServiceBehavior>()
                .Count();
            Assert.That(serviceBehaviorCount, Is.EqualTo(0));
        }
コード例 #23
0
 private static ServiceHost CreateTestServiceHost(ILifetimeScope container)
 {
     var host = new ServiceHost(typeof(TestService), TestServiceAddress);
     host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "");
     host.AddDependencyInjectionBehavior<ITestService>(container);
     host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = TestServiceAddress });
     return host;
 }