简体   繁体   中英

Using Autofac with Web Api 2 and Owin

Im new to DI libraries and trying to use Autofac in a WebApi 2 project with Owin. This is my Owin Startup class,

[assembly: OwinStartup(typeof(FMIS.SIGMA.WebApi.Startup))]
namespace FMIS.SIGMA.WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            ConfigureOAuth(app);
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        }

    }
}

When I call a Api method I get this error

An error occurred when trying to create a controller of type 'MyController'. Make sure that the controller has a parameterless public constructor.

What am I missing here?


MyController code is something like this

public class MyController : ApiController
    {
        ISomeCommandHandler someCommanHandler;

        public MyController(ISomeCommandHandler SomeCommandHandler)
        {
            this.someCommanHandler = SomeCommandHandler;

        }

        // POST: api/My
        public void Post([FromBody]string value)
        {
            someCommanHandler.Execute(new MyCommand() { 
                Name = "some value"
            });
        }

        // GET: api/My
        public IEnumerable<string> Get()
        {

        }

        // GET: api/My/5
        public string Get(int id)
        {

        }
    }

You have set DependencyResolver to AutofacWebApiDependencyResolver , so Autofac comes into play and instantiates dependencies for you. Now you have to explicitly tell Autofac which concrete implementations should be used when an instance of interface is required.

Your controller requires an instance of ISomeCommandHandler :

MyController(ISomeCommandHandler SomeCommandHandler)

So you need to configure types that expose that interface:

builder.RegisterType<CommandHandler>.As<ISomeCommandHandler>();

Have a look at this documentation section for more examples about Autofac registration concepts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM