Skip to content

Instantly share code, notes, and snippets.

@bitplus
Forked from ovrmrw/Program.cs
Created September 28, 2021 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitplus/a7ae58127c030173b2348305a3e18890 to your computer and use it in GitHub Desktop.
Save bitplus/a7ae58127c030173b2348305a3e18890 to your computer and use it in GitHub Desktop.
Topshelf + OWIN Self-Host + ASP.NET WebAPI + Ninject
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Tracing;
using System.Reflection;
using Owin;
using Microsoft.Owin.Hosting;
using Topshelf;
using Topshelf.ServiceConfigurators;
using Ninject;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
var exitCode = HostFactory.Run(c =>
{
c.Service<MyService>(service =>
{
ServiceConfigurator<MyService> s = service;
s.ConstructUsing(() => new MyService());
s.WhenStarted(a => a.Start());
s.WhenStopped(a => a.Stop());
});
});
return (int)exitCode;
}
}
public class MyService
{
private IDisposable app;
public void Start()
{
app = WebApp.Start("http://localhost:5000/");
}
public void Stop()
{
app.Dispose();
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(config.Formatters.JsonFormatter);
config.EnableSystemDiagnosticsTracing();
app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config);
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
//kernel.Load(Assembly.GetExecutingAssembly());
DependencyInjection(kernel);
return kernel;
}
private static void DependencyInjection(IKernel kernel)
{
kernel.Bind<ISampleDependency>().To<SampleDependency1>();
}
}
public class SampleController : ApiController
{
private ISampleDependency _dependency;
public SampleController(ISampleDependency dependency)
{
_dependency = dependency;
}
[Route("")]
[HttpGet]
public IHttpActionResult GetRoot()
{
return Ok<string>("This is root.");
}
[Route("{id:int}")]
[HttpGet]
public IHttpActionResult GetSquare(int id)
{
int value;
try
{
value = _dependency.Square(id);
}
catch
{
return NotFound();
}
return Ok<int>(value);
}
[Route("{id}")]
[HttpGet]
public IHttpActionResult GetString(string id)
{
return Ok<string>(string.Format("get string: {0}", id));
}
}
public interface ISampleDependency
{
int Square(int id);
}
public class SampleDependency1 : ISampleDependency
{
public int Square(int id)
{
return id * id;
}
}
public class SampleDependency2 : ISampleDependency
{
public int Square(int id)
{
return id * id * id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment