csharp 示例Topshelf服务,演示如何使用Fooidity Switchyard切换功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 示例Topshelf服务,演示如何使用Fooidity Switchyard切换功能相关的知识,希望对你有一定的参考价值。

namespace ConsoleApplication2
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Autofac;
    using Fooidity;
    using Topshelf;


    class Program
    {
        static int Main(string[] args)
        {
            return (int)HostFactory.Run(x =>
            {
                x.Service(hostSettings => ServiceContainer.Container.Resolve<SampleService>(),
                    s => { s.AfterStoppingService(() => ServiceContainer.Container.Dispose()); });
            });
        }
    }


    class ServiceContainer
    {
        static readonly Lazy<IContainer> _container = new Lazy<IContainer>(CreateServiceContainer);

        public static IContainer Container
        {
            get { return _container.Value; }
        }

        static IContainer CreateServiceContainer()
        {
            var builder = new ContainerBuilder();

            builder.ConfigureFoodityClient(x =>
            {
                x.Host("http://api.fooidity.com/");
                x.ApplicationKey("put your application key here from the web site");
            });

            builder.RegisterCodeSwitch<TestFeature>();

            builder.RegisterType<SampleService>();

            return builder.Build();
        }
    }


    class SampleService :
        ServiceControl
    {
        readonly CancellationTokenSource _cancel;
        readonly ILifetimeScope _scope;

        public SampleService(ILifetimeScope scope)
        {
            _scope = scope;
            _cancel = new CancellationTokenSource();

            Task.Run(() => Background(_cancel.Token));
        }

        public bool Start(HostControl hostControl)
        {
            Console.WriteLine("Started the service");

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            Console.WriteLine("Stopped the service");

            _cancel.Cancel();
            return true;
        }

        async Task Background(CancellationToken cancellationToken)
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(1000, cancellationToken);

                using (ILifetimeScope scope = _scope.BeginLifetimeScope())
                {
                    Console.WriteLine("Switch: {0}", scope.Resolve<ICodeSwitch<TestFeature>>().Enabled);
                }
            }
        }
    }


    public struct TestFeature :
        ICodeFeature
    {
    }
}

以上是关于csharp 示例Topshelf服务,演示如何使用Fooidity Switchyard切换功能的主要内容,如果未能解决你的问题,请参考以下文章

csharp C#中的Topshelf使用

csharp C#中的Topshelf使用

csharp Topshelf与Windsor的基本用法

使用.NET Core创建Windows服务 - 使用Topshelf方式

csharp Topshelf + OWIN自主机+ ASP.NET WebAPI + Ninject

使用 Topshelf 创建 Windows 服务