Web Api dependency injection

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
11 лет назад
Hello,

I'm writing a plugin that uses web api controller (for kendo ui databinding).

Can anyone provide me an example of how to use dependency injection (autofac) to inject NopCommerce service interface into Web Api Controller constructor?

Thanks.
10 лет назад
Hi, did you reach a conclusion on that matter?
10 лет назад
No. I'v postponed development for a while.
Wanted to create attributes filter with dropdowns...
But ended using kendo window ui temporarily (fast and easy solution).
10 лет назад
Maybe this article could be helpful
10 лет назад
I am doing something similar. I am getting decent results by creating a separate project in the presentation section called Nop.Web.Api, and adding this as a reference to Nop.Web

To get this to work, you may want to start with a Web Api project template, and then just add in the Autofac.WebApi reference mentioned in that link.

The default WebApiConfig file will look something like this:

 public static void Register(HttpConfiguration config)
        {
            // Route for POST method

            config.Routes.MapHttpRoute(
            name: "DefaultApi2",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );

            //   Route  GET method

            config.Routes.MapHttpRoute(
               name: "DefaultApi1",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { action = "get", id = RouteParameter.Optional }
            );
            }


You will need to call the Register function in Nop.Web App_Start. Believe it or not, you can fire simple test api functions returning hard coded strings and such with just that in place. However, to register dependencies and use anything remotely useful in Nop.Core.Services, you have to add something like this to your WebApiConfig.cs


var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // We have to register services specifically for the API calls!
            builder.RegisterType<BlogService>()
                      .AsImplementedInterfaces().InstancePerLifetimeScope();


Notice the InstancePerLifetimeScope call. I have no idea why this is required, but trust me, it works. That should get you started.

Personally, I am running into issues serializing the complex objects which Nop.Services slings around. Part of the problem is that the objects are based on Entity Framework, and I haven't figured out how to turn off proxy class generation, which creates circular references the XMLformatter cannot handle. Apparently the jsonformatter is a little more robust in this respect, but nonetheless, that's where I'm hung up.
10 лет назад
Kind of an old question but for anyone else who wants to play with a Web API application here is a kind of a hacky workaround to only register your dependencies once while still using autofac.

As per this and this post InstancePerHttpRequest and InstancePerApiRequest share the same tag.

The actual code from the previous post is correct but in order to only register our dependencies once and call Build() once(which is all that is supported) we need access to the container.

NopEngine.cs creates the ContainerBuilder and calls build on it.  All we need to do is add IContainer as an additional parameter to ContainerConfigurer and pass in the container from NopEnginge.InitializeContainer.


private void InitializeContainer(ContainerConfigurer configurer, EventBroker broker, NopConfig config)
        {
            var builder = new ContainerBuilder();
            var container = builder.Build();

            _containerManager = new ContainerManager(container);
            configurer.Configure(this, _containerManager, broker, config, container);
        }


Then from ContainerConfigure.Configure we need to create our webApiResolver (because web api takes GlobalConfiguration.Configuration.DependencyResolver not  DependencyResolver.SetResolver).  Add this after containerManager.UpdateContainer.


var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;


Now this would appear to be all we need to do but Autofac will only be looking for MVC type controllers and won't find any Web API controllers.  Alter this section of code in Nop.Web.Framework.DependencyRegistrar.

var assemblies = typeFinder.GetAssemblies().ToArray();
builder.RegisterControllers(assemblies);
builder.RegisterApiControllers(assemblies);


That's it.  You can now add a Web API project to your solution and use all the services from Nop.Services.

Admittedly this is not the most elegant solution.  In fact it's a bit hacky.  But its a quick way to get started using Web API.

t.

UPDATE: Using this method also allows you to use client side frameworks like AngularJs and "dog food" your own api.
7 лет назад
EnableCrossSiteRequests(config);
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
           config.DependencyResolver = new AutofacWebApiDependencyResolver(EngineContext.Current.ContainerManager.Container);



I have registered in this way , it's is working in Local , but not on Goddady Server,Checked Every thing ,Setting.txt file etc , but no Luck still now :(
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.