Ninject working with WCF Web API Preview 5

隐身守侯 提交于 2019-11-30 19:03:27
zanewill

Following is my code with Ninject and WebApi,it works. Create a class inherites from WebApiConfiguration

public class NinjectWebApiConfiguration : WebApiConfiguration {
    private IKernel kernel = new StandardKernel();

    public NinjectWebApiConfiguration() {
        AddBindings();
        CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);
    }

    private void AddBindings() {
        kernel.Bind<IProductRepository>().To<MockProductRepository>();
    }

}

and use the NinjectWebApiConfiguration in RegisterRoutes

public static void RegisterRoutes(RouteCollection routes) {

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    var config = new NinjectWebApiConfiguration() { 
        EnableTestClient = true
    };

    routes.MapServiceRoute<ContactsApi>("api/contacts", config);
}

In P5 you have to derive from WebApiConfiguration and use your derived configuration:

public class NinjectConfiguration : WebApiConfiguration
    {
        public NinjectConfiguration(IKernel kernel)
        {
            CreateInstance((t, i, m) =>
            {
                return kernel.Get(t);
            }); 
        }
    }

There are great answers to the question here but I would like to show you the way with default WebApi configuration:

    protected void Application_Start(object sender, EventArgs e) {

        RouteTable.Routes.SetDefaultHttpConfiguration(new Microsoft.ApplicationServer.Http.WebApiConfiguration() { 
            CreateInstance = (serviceType, context, request) => GetKernel().Get(serviceType)
        });

        RouteTable.Routes.MapServiceRoute<People.PeopleApi>("Api/People");
    }

    private IKernel GetKernel() { 

        IKernel kernel = new StandardKernel();

        kernel.Bind<People.Infrastructure.IPeopleRepository>().
            To<People.Models.PeopleRepository>();

        return kernel;
    }

The below blog post talks a little bit about Ninject integration on WCF Web API:

http://www.tugberkugurlu.com/archive/introduction-to-wcf-web-api-new-rest-face-ofnet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!