ninject / Ninject.Web.Common

It provides the base infrastructure for all web type extension
Other
56 stars 40 forks source link

Ninject self host WebAPI? #31

Open KevinBurton opened 8 years ago

KevinBurton commented 8 years ago

In the documentation that wasn't an mention on how to create self hosted Web API with Ninject? WHat name space should I look under? Thank you.

KevinBurton commented 8 years ago

Here is my configuration that seems to break the WebAPI routes:

        const string WEBSOCKETSERVER = "localhost";
        const int WEBSOCKETPORT = 8080;
        var webApiConfig = new HttpSelfHostConfiguration((WEBSOCKETPORT == 80 ? string.Format("http://{0}", WEBSOCKETSERVER) : string.Format("http://{0}:{1}", WEBSOCKETSERVER, WEBSOCKETPORT)));

        // Web API routes
        webApiConfig.MapHttpAttributeRoutes();

        webApiConfig.Routes.MapHttpRoute(
            name: "Default API",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        var appXmlType = webApiConfig.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        webApiConfig.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
        var server = new NinjectSelfHostBootstrapper(CreateKernel, webApiConfig);
        server.Start();

Changing the last two lines to

      var server = new HttpSelfHostServer(webApiConfig);
      server.OpenAsync().Wait();

Makes the routes work but Ninject is hosed then.

What am I doing wrong? Thank you.

KevinBurton commented 8 years ago

I see an example for WCF that includes a call like:

var someWcfService = NinjectWcfConfiguration.Create<MyWcfService, NinjectServiceSelfHostFactory>();

But I cannot seem to find an equivalent extension for WEB Api. Ideas?

scotmeiste commented 8 years ago

Not sure if this is still an issue, but I've had a lot of success with Ninject and WebApi using OWIN as the self-hosting infrastructure.

Here's my start-up class (code to setup security has been omitted for brevity):

 public class Startup
 {
     public void Configuration(IAppBuilder app)
     {
         var config = new HttpConfiguration();
         var kernel = CreateKernel();

         config.MapHttpAttributeRoutes();

         app.UseNinjectMiddleware(() => kernel);
         app.UseNinjectWebApi(config);
     }

     private static StandardKernel CreateKernel()
     {
         var kernel = new StandardKernel();
         kernel.Load(new DependencyInjectionModule());

         return kernel;
     }
}

Here's how to set it up: https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-a-OWIN-WebApi-application

Niklas-Peter commented 8 years ago

In .NET 4.0 OWIN self host is not available. How can I use the classic self host (Microsoft.AspNet.WebApi.SelfHost) with Ninject?

The slightly changed code from the wiki is not working:

    var config = new HttpSelfHostConfiguration("http://localhost:8080");
        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        var selfHost = new NinjectSelfHostBootstrapper(CreateKernel, config);
        selfHost.Start();

    public static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        kernel.Bind<IService>().To<Service>();
        return kernel;
    }

The web server is obviously not even started. No exception, but requests created from a web browser and using HttpClient result in a connection

If I do it this way instead of leveraging the NinjectSelfHostBootsrapper and use https://github.com/sethwebster/NinjectDependencyResolver/blob/master/Ninject.WebApi.DependencyResolver/NinjectDependencyResolver.cs as DependencyResolver it works.

        var config = new HttpSelfHostConfiguration("http://localhost:8080");

        config.DependencyResolver = new NinjectDependencyResolver(CreateKernel());

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            ListAllProducts();
        }