public ServiceHost Initialize()
 {
     _serviceHost = CreateServiceHost();
     _serviceHost.AddDependencyInjectionBehavior <TContract>(_lifetimeScope);
     _serviceHost.Open();
     return(_serviceHost);
 }
        public async Task Fact1()
        {
            IServiceCollection services = new ServiceCollection();

            services.AddScoped <ITestService, TestServicePerCall>();
            services.AddSingleton(new Dependency {
                Initial = 1
            });

            using (var provider = services.BuildServiceProvider())
            {
                using (ServiceHost host = new ServiceHost(typeof(TestServicePerCall), new Uri("net.tcp://localhost:5000")))
                {
                    host.AddServiceEndpoint(typeof(ITestService), binding, "/service1");
                    host.AddDependencyInjectionBehavior <ITestService>(provider);

                    await host.OpenAsync();

                    using (var client = ChannelFactory <ITestServiceClient> .CreateChannel(binding, new EndpointAddress("net.tcp://localhost:5000/service1")))
                    {
                        var result = client.Operation();
                        Assert.Equal(2, result);
                        result = client.Operation();
                        Assert.Equal(2, result);
                    }

                    await host.CloseAsync();
                }
            }
        }
Exemplo n.º 3
0
        public static void Main()
        {
            Console.Title = "Server";

            AppDomain.CurrentDomain.UnhandledException   += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

            var builder = new ContainerBuilder();

            builder.RegisterType <MyServiceImplementation>().As <IMyService>();

            // == Register mutator via Autofac, currently done via NServiceBus bus configuration. See below!
            // builder.RegisterType<MyMutator>().AsImplementedInterfaces().AsSelf().InstancePerLifetimeScope();

            builder.RegisterType <MyUnitOfWork>().AsImplementedInterfaces().InstancePerLifetimeScope();

            var container = builder.Build();

            InitBus(container);

            using (var host = new ServiceHost(typeof(MyServiceImplementation)))
            {
                host.AddDependencyInjectionBehavior <IMyService>(container);
                host.Open();
                Console.WriteLine("Press *any* key to quit");
                Console.ReadKey();
                host.Close();
            }
        }
Exemplo n.º 4
0
        public void Run()
        {
            var baseAddress = new Uri("https://localhost:8080/hello");

            _host = new ServiceHost(typeof(UserAdmin), baseAddress);

            var smb = new ServiceMetadataBehavior
            {
                HttpsGetEnabled  = true,
                MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 }
            };

            _host.Description.Behaviors.Add(smb);
            var mexBinding = MetadataExchangeBindings.CreateMexHttpsBinding();

            _host.AddServiceEndpoint(
                ServiceMetadataBehavior.MexContractName,
                mexBinding,
                "mex"
                );
            _host.Credentials.ServiceCertificate.Certificate = new X509Certificate2("c:\\temp\\TempCA.pfx");
            var binding = new BasicHttpBinding
            {
                Security =
                {
                    Mode = BasicHttpSecurityMode.Transport,
                }
            };

            _host.AddServiceEndpoint(typeof(IUserAdmin), binding, "");
            _host.Authorization.ServiceAuthorizationManager = new WcfServiceAuthorizationManager();
            _host.Description.Behaviors.Find <ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
            _host.AddDependencyInjectionBehavior <IUserAdmin>(_scope);
            _host.Open();
        }
Exemplo n.º 5
0
        static void HostNetTcpService(IContainer container)
        {
            // Create two different URIs to serve as the base address
            // One for http requests and another for net.tcp
            Uri netTcpUrl = new Uri("net.tcp://localhost:8080/ArticleNetTcpService");

            //Create ServiceHost to host the service in the console application
            netTcpHost = new ServiceHost(typeof(ArticleService), netTcpUrl);

            // Enable metadata exchange - you need this so others can create proxies
            // to consume your WCF service
            ServiceMetadataBehavior serviceMetaBehavior = new ServiceMetadataBehavior();

            netTcpHost.Description.Behaviors.Add(serviceMetaBehavior);

            netTcpHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

            // Set dependency injection
            netTcpHost.AddDependencyInjectionBehavior <IArticleService>(container);

            // Start the Service
            netTcpHost.Open();

            Console.WriteLine("IArticleService Service is host at " + DateTime.Now.ToString());
            Console.WriteLine();
        }
Exemplo n.º 6
0
        private void AddFleeterService()
        {
            var endpoint = new Uri(baseEndpoint + "fleeter");

            var host = new ServiceHost(typeof(FleeterService), endpoint);

            host.AddServiceEndpoint(typeof(IFleeterService), new WSHttpBinding(), "");
            host.AddDependencyInjectionBehavior <IFleeterService>(_lifetimeScope);

            host.Description.Behaviors.Add(new ServiceMetadataBehavior {
                HttpGetEnabled = true, HttpsGetEnabled = true
            });

            try
            {
                host.Open();
                log.LogInformation($"Started FleeterService on {endpoint}");
            }
            catch (Exception ex)
            {
                log.LogError(ex, $"Could not start FleeterService {endpoint}");
            }

            _services.Add(host);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            // Register your service implementations.
            builder.RegisterModule(new WcfServices.AutofacModule());
            //var container = builder.Build();

            using (var container = builder.Build())
            {
                //Uri address = new Uri("http://localhost:9001/NoteService");
                ServiceHost host = new ServiceHost(typeof(NoteService));//, address);
                //host.AddServiceEndpoint(typeof(INoteService), new BasicHttpBinding(), string.Empty);

                // Here's the important part - attaching the DI behavior to the service host
                // and passing in the container.
                host.AddDependencyInjectionBehavior <INoteService>(container);

                //host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true, HttpGetUrl = address });
                host.Open();

                ServiceHost host2 = new ServiceHost(typeof(UserService));//, address);
                host2.AddDependencyInjectionBehavior <IUserService>(container);
                host2.Open();

                Console.WriteLine("The hosts have been opened.");
                Console.ReadLine();

                host.Close();
                Environment.Exit(0);
            }
        }
Exemplo n.º 8
0
        public static void Main(string[] args)
        {
            using (var container = AutofacConfig.Configure())
            {
                var uri = new Uri(ConfigurationManager.AppSettings["uri"]);
                using (var serviceHost = new ServiceHost(typeof(RemoteNotesService), uri))
                {
                    var logger = container.Resolve <IRemoteNotesLogger <Program> >();

                    try
                    {
                        serviceHost.AddDependencyInjectionBehavior <IRemoteNotesService>(container);
                        serviceHost.Open();

                        logger.Info($"Service {uri} was running.");

                        Console.WriteLine("Press any key to exit...");
                        Console.ReadKey();

                        serviceHost.Close();
                        logger.Info($"Service {uri} was stopped.");
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"The following exception was thrown: '{ex.Message}'. Stack trace: '{ex.StackTrace}'.");

                        Console.WriteLine("Press any key to exit...");
                        Console.ReadKey();
                    }
                }
            }
        }
Exemplo n.º 9
0
        static void Main()
        {
            var assemblies = GetAssemblies();

            var types = assemblies
                        .SelectMany(assembly => assembly.GetTypes())
                        .Where(type => type.IsClass && type.GetInterfaces().Any(y => y.IsDefined(typeof(ServiceContractAttribute))))
                        .ToList();

            var container = Bootstrapper.BuildContainer(assemblies);

            Console.WriteLine("ServiceHost");
            try
            {
                foreach (var type in types)
                {
                    var serviceHost = new ServiceHost(type);
                    serviceHost.AddDependencyInjectionBehavior(type, container);
                    serviceHost.Open();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.WriteLine("Started");
            Console.ReadKey();
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Container = AutofacBuilder.ConfigByJson(JSON_FILE_NAME);

            //using (ServiceHost host = new ServiceHost(typeof(WcfConversationService)))
            //{
            //    host.AddDependencyInjectionBehavior<IWcfConversationService>(Container);

            //    host.Open();

            //    Console.WriteLine("Service hosted successfully");

            //    Console.ReadKey(true);
            //}

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

            host.AddDependencyInjectionBehavior <IWcfConversationService>(Container);

            host.Open();
            foreach (var item in host.BaseAddresses)
            {
                Console.WriteLine(item.AbsoluteUri);
            }
            Console.WriteLine("Service hosted successfully");

            Console.ReadKey(true);
        }
Exemplo n.º 11
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            var builder = new ContainerBuilder();

            // TODO: separate these to modules
            builder.RegisterType <UserService>().As <IUserService>();
            builder.RegisterType <MappingService>().As <IMappingService>();
            builder.RegisterType <Service.Implementation.UserService>().As <Service.Contracts.IUserService>();
            builder.RegisterType <GuidWrapper>().As <IGuidWrapper>();
            builder.RegisterType <DateTimeWrapper>().As <IDateTimeWrapper>();
            builder.RegisterType <UserStore>().As <IStore <User> >();
            builder.RegisterType <UserQuery>().As <IUserQuery>();

            var mapperConfig = new MapperConfigurationExpression();

            new WcfMappingConfiguration().Configure(mapperConfig);
            new EfCoreMappingConfiguration().Configure(mapperConfig);

            Mapper.Initialize(mapperConfig);

            using (var container = builder.Build())
            {
                using (var serviceHost = new ServiceHost(typeof(UserService)))
                {
                    serviceHost.AddDependencyInjectionBehavior <IUserService>(container);
                    serviceHost.Open();

                    Console.WriteLine("The service is listening...");
                    Console.WriteLine("Press <Enter> to stop the service.");
                    Console.ReadLine();
                }
            }
        }
        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();
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            IContainer       container = null;
            ContainerBuilder builder   = new ContainerBuilder();

            builder.RegisterAssemblyTypes(typeof(ZipCodeRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .As(t => t.GetInterfaces().FirstOrDefault(
                    i => i.Name == "I" + t.Name));

            builder.RegisterType <GeoManager>();

            container = builder.Build();

            ServiceHost hostGeoManager = new ServiceHost(typeof(GeoManager));

            hostGeoManager.AddDependencyInjectionBehavior(typeof(GeoManager), container);

            hostGeoManager.Open();

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

            hostGeoManager.Close();
        }
Exemplo n.º 14
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();
            }
        }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF7;
            try
            {
                var authHost         = new ServiceHost(typeof(AuthService));
                var registrationHost = new ServiceHost(typeof(RegistrationService));
                var userHost         = new ServiceHost(container.Resolve <UserService>());

                authHost.AddDependencyInjectionBehavior <AuthService>(container);
                registrationHost.AddDependencyInjectionBehavior <RegistrationService>(container);
                userHost.AddDependencyInjectionBehavior <UserService>(container);

                userHost.Open();
                Console.WriteLine("User Service Started...");
                authHost.Open();
                Console.WriteLine("Auth Service Started...");
                registrationHost.Open();
                Console.WriteLine("Register Service Started...");

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Exemplo n.º 16
0
 public static void Main(string[] args)
 {
     using (var host = new ServiceHost(typeof(NameService)))
     {
         //host.AddServiceEndpoint(typeof(INameService), new BasicHttpBinding(), "http://localhost:46468/NameService");
         //host.AddServiceEndpoint(typeof(INameService), new BasicHttpBinding(), "http://localhost:9562/NameService");
         //if(host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
         //{
         //    var metadataBehavior = new ServiceMetadataBehavior();
         //    metadataBehavior.HttpGetEnabled = true;
         //    metadataBehavior.HttpGetUrl =  new Uri("http://localhost:46468/NameService/meta");
         //    host.Description.Behaviors.Add(metadataBehavior);
         //    host.Opened += Host_Opened;
         //    host.Open();
         //    Console.ReadKey();
         //}
         host.Opened += Host_Opened;
         host.Open();
         ContainerBuilder containerBuilder = new ContainerBuilder();
         containerBuilder.RegisterType <Services>().As <IServices>();
         host.AddDependencyInjectionBehavior <IServices>(containerBuilder.Build());
         Console.ReadKey();
     }
     Console.WriteLine("hello word");
 }
Exemplo n.º 17
0
        private static void EndPointIntilaize(Autofac.IContainer container, BasicHttpBinding bind)
        {
            Uri         address = new Uri("http://localhost:8081/test/");
            ServiceHost host    = new ServiceHost(typeof(Test1Service), address);

            host.AddServiceEndpoint(typeof(ITest1Service), bind, string.Empty);

            host.AddDependencyInjectionBehavior <ITest1Service>(container);
            host.Description.Behaviors.Add(new ServiceMetadataBehavior {
                HttpGetEnabled = true, HttpGetUrl = address
            });
            host.Open();

            Uri         address2 = new Uri("http://localhost:8081/user/");
            ServiceHost host2    = new ServiceHost(typeof(UserService), address2);

            host2.AddServiceEndpoint(typeof(IUserService), bind, string.Empty);
            host2.AddDependencyInjectionBehavior <IUserService>(container);
            host2.Description.Behaviors.Add(new ServiceMetadataBehavior {
                HttpGetEnabled = true, HttpGetUrl = address2
            });
            host2.Open();



            Uri         address4 = new Uri("http://localhost:8081/RoleService/");
            ServiceHost host4    = new ServiceHost(typeof(RoleService), address4);

            host4.AddServiceEndpoint(typeof(IRoleService), bind, string.Empty);
            host4.AddDependencyInjectionBehavior <IRoleService>(container);
            host4.Description.Behaviors.Add(new ServiceMetadataBehavior {
                HttpGetEnabled = true, HttpGetUrl = address4
            });
            host4.Open();
        }
Exemplo n.º 18
0
        public void AddDependencyInjectionBehavior_NullContainer_ThrowsException()
        {
            ServiceHost           serviceHost = new ServiceHost(typeof(ServiceType));
            ArgumentNullException exception   = Assert.Throws <ArgumentNullException>(
                () => serviceHost.AddDependencyInjectionBehavior(typeof(IContractType), null));

            Assert.That(exception.ParamName, Is.EqualTo("container"));
        }
        public void AddDependencyInjectionBehavior_NullParameters_ThrowsException()
        {
            ServiceHost           serviceHost = new ServiceHost(typeof(ServiceType));
            ArgumentNullException exception   = Assert.Throws <ArgumentNullException>(
                () => serviceHost.AddDependencyInjectionBehavior(typeof(IContractType), new ContainerBuilder().Build(), null));

            Assert.Equal("parameters", exception.ParamName);
        }
        public bool Start()
        {
            host = new ServiceHost(typeof(HelloWorldService));
            host.AddDependencyInjectionBehavior <IHelloWorldService>(scope);
            host.Open();

            logger.Info("The host has been opened.");
            return(true);
        }
Exemplo n.º 21
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().WithParameter(new TypedParameter(typeof(string), "DefaultConnection"));
            builder.RegisterType <Test1Service>().As <ITest1Service>();
            builder.RegisterType <UserService>().As <IUserService>();
            builder.RegisterType <Service.RoleService>().As <IRoleService>();
            var bind = new BasicHttpBinding
            {
                MaxBufferPoolSize      = int.MaxValue,
                MaxBufferSize          = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                ReceiveTimeout         = TimeSpan.MaxValue,
                OpenTimeout            = TimeSpan.MaxValue,
                SendTimeout            = TimeSpan.MaxValue,
                TransferMode           = TransferMode.Buffered
            };

            using (var container = builder.Build())
            {
                Uri         address = new Uri("http://localhost:8081/test/");
                ServiceHost host    = new ServiceHost(typeof(Test1Service), address);
                host.AddServiceEndpoint(typeof(ITest1Service), bind, string.Empty);

                host.AddDependencyInjectionBehavior <ITest1Service>(container);
                host.Description.Behaviors.Add(new ServiceMetadataBehavior {
                    HttpGetEnabled = true, HttpGetUrl = address
                });
                host.Open();
                _logger.LogInformation("The host of " + host.Description.Name.ToString() + " has been opened.");

                Uri         address2 = new Uri("http://localhost:8081/user/");
                ServiceHost host2    = new ServiceHost(typeof(UserService), address2);
                host2.AddServiceEndpoint(typeof(IUserService), bind, string.Empty);
                host2.AddDependencyInjectionBehavior <IUserService>(container);
                host2.Description.Behaviors.Add(new ServiceMetadataBehavior {
                    HttpGetEnabled = true, HttpGetUrl = address2
                });
                host2.Open();
                _logger.LogInformation("The host of " + host2.Description.Name.ToString() + " has been opened.");



                Uri         address4 = new Uri("http://localhost:8081/RoleService/");
                ServiceHost host4    = new ServiceHost(typeof(RoleService), address4);
                host4.AddServiceEndpoint(typeof(IRoleService), bind, string.Empty);
                host4.AddDependencyInjectionBehavior <IRoleService>(container);
                host4.Description.Behaviors.Add(new ServiceMetadataBehavior {
                    HttpGetEnabled = true, HttpGetUrl = address4
                });
                host4.Open();
                _logger.LogInformation("The host of " + host4.Description.Name.ToString() + " has been opened.");
                return(ExecuteAsync(stoppingToken));
            }
        }
Exemplo n.º 22
0
        static void HostServices()
        {
            using (var container = InitBuilder().Build())
            {
                // Create two different URIs to serve as the base address
                // One for http requests and another for net.tcp
                Uri httpUrl   = new Uri("http://localhost:8090/BlogHttpService");
                Uri netTcpUrl = new Uri("net.tcp://localhost:8080/ArticleNetTcpService");

                //Create ServiceHost to host the service in the console application
                httpHost   = new ServiceHost(typeof(BlogService), httpUrl);
                netTcpHost = new ServiceHost(typeof(ArticleService), netTcpUrl);

                // Enable metadata exchange - you need this so others can create proxies
                // to consume your WCF service
                ServiceMetadataBehavior httpServiceMetaBehavior   = new ServiceMetadataBehavior();
                ServiceMetadataBehavior netTcpServiceMetaBehavior = new ServiceMetadataBehavior();
                httpHost.Description.Behaviors.Remove(typeof(ServiceDebugBehavior));
                httpHost.Description.Behaviors.Add(
                    new ServiceDebugBehavior {
                    IncludeExceptionDetailInFaults = true
                });

                httpServiceMetaBehavior.HttpGetEnabled = true;
                httpHost.Description.Behaviors.Add(httpServiceMetaBehavior);
                netTcpHost.Description.Behaviors.Add(netTcpServiceMetaBehavior);

                netTcpHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

                // Set dependency injection
                httpHost.AddDependencyInjectionBehavior <IBlogService>(container);
                netTcpHost.AddDependencyInjectionBehavior <IArticleService>(container);

                // Start the Services
                httpHost.Open();
                netTcpHost.Open();

                Console.WriteLine("IBlogService Service is host at " + DateTime.Now.ToString());
                Console.WriteLine("IArticleService Service is host at " + DateTime.Now.ToString());
                Console.WriteLine();

                Console.WriteLine("Press any key to terminate..");
                Console.ReadKey();

                if (httpHost != null && httpHost.State == CommunicationState.Opened)
                {
                    httpHost.Close();
                }

                if (netTcpHost != null && netTcpHost.State == CommunicationState.Opened)
                {
                    netTcpHost.Close();
                }
            }
        }
Exemplo n.º 23
0
        public ServerManager(IContainer container)
        {
            this.container = container;


            serviceHost = new ServiceHost(typeof(T));
            serviceHost.AddDependencyInjectionBehavior <T1>(container);
            serviceHost.Faulted += ServiceHostFaulted;
            serviceHost.UnknownMessageReceived += ServiceHostUnknownMessageReceived;
            serviceHost.Description.Behaviors.Add(container.Resolve <HtmlServiceBehavior>());
        }
Exemplo n.º 24
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);
        }
        public void Fact3()
        {
            using (ServiceHost host = new ServiceHost(typeof(TestServiceSingle), new Uri("net.tcp://localhost:5002")))
            {
                using (var provider = new ServiceCollection().BuildServiceProvider())
                {
                    host.AddDependencyInjectionBehavior <ITestService>(provider);

                    Assert.False(host.Description.Behaviors.Contains(typeof(ServiceProviderServiceBehavior)));
                }
            }
        }
Exemplo n.º 26
0
        public DeployerServiceHost(Uri baseAddress, ILifetimeScope lifetimeScope)
        {
            _host = new ServiceHost(typeof(DeployerService), baseAddress);
            var binding = new WSHttpBinding {
                Security = { Mode = SecurityMode.None }
            };
            var endpoint  = _host.AddServiceEndpoint(typeof(IDeployerService), binding, typeof(IDeployerService).Name);
            var container = new ContainerAdapter(lifetimeScope);

            _host.AddDependencyInjectionBehavior <IDeployerService>(container);
            TraceHelper.TraceInformation(TraceSwitches.TfsDeployer, "DeployerService will listen at {0}", endpoint.ListenUri);
        }
        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);
        }
Exemplo n.º 28
0
 public HostedWcfService(IServiceProvider serviceProvider)
 {
     if (ServiceDescription.GetService(typeof(TService)).IsInstanceContextModeSingle())
     {
         host = new ServiceHost(serviceProvider.GetRequiredService <TContract>());
     }
     else
     {
         host = new ServiceHost(typeof(TService));
         host.AddDependencyInjectionBehavior <TContract>(serviceProvider);
     }
 }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            // Workaround the CLR Threadpool issue
            ThreadPoolTimeoutWorkaround.DoWorkaround();
            IContainer container = CreateContainer();

            var benchmarkService = new ServiceHost(typeof(BenchmarkService));

            benchmarkService.AddDependencyInjectionBehavior <BenchmarkService>(container);
            benchmarkService.Open();
            Console.WriteLine("service is up");
            Console.ReadLine();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Start the module.
        /// </summary>
        public override void Start()
        {
            base.Start();
            try
            {
                ServiceHost = new ServiceHost(typeof(ClientConnectorReal));

                //autofac DI
                ServiceHost.AddDependencyInjectionBehavior <IClientConnector>(IocManager.Container);

                //绑定服务行为
                ServiceMetadataBehavior behavior = ServiceHost.Description.Behaviors.
                                                   Find <ServiceMetadataBehavior>();

                if (behavior == null)
                {
                    behavior = new ServiceMetadataBehavior();
                    behavior.HttpGetEnabled = true;
                    ServiceHost.Description.Behaviors.Add(behavior);
                }
                else
                {
                    behavior.HttpGetEnabled = true;
                }

                //启动事件
                ServiceHost.Opened += delegate
                {
                    var Logger = LoggerPool.GetLogger("");
                    Logger.Info("Host-->Endpoint:" + ServiceHost.Description.Endpoints.FirstOrDefault().Address);
                    Logger.Info("Host-->Service started:" + ServiceHost.Description.ConfigurationName);
                };

                ServiceHost.Closed += delegate
                {
                    var Logger = LoggerPool.GetLogger("");
                    Logger.Info("Host-->Endpoint:" + ServiceHost.Description.Endpoints.FirstOrDefault().Address);
                    Logger.Info("Host-->Service closed:" + ServiceHost.Description.ConfigurationName);
                };

                Thread th = new Thread(ServiceHost.Open);
                th.Start();

                IocManager.Register <IServiceHostProvider>(new DefaultServiceHostProvider(ServiceHost));
            }
            catch (Exception ex)
            {
                var Logger = LoggerPool.GetLogger("");
                Logger.Error(ex.Message, ex);
            }
        }