【问题标题】:Parameterless constructor error with autofac in web api 2web api 2中autofac的无参数构造函数错误
【发布时间】:2015-12-01 22:17:14
【问题描述】:

我使用 Autofac 作为 IOC,这是我的结构:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdTudent.Repo
{
    public interface IRepository
    {
        IAdvertisementRepository Advertisements { get; set; }
        IProfileRepository Profiles { get; set; }
    }
}

我的存储库类是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdTudent.Repo
{
    public class Repositories : IRepository
    {
        public Repositories(IAdvertisementRepository advertisementRepository,
                            IProfileRepository profileRepository)
        {
            Advertisements = advertisementRepository;
            Profiles = profileRepository;
        }
        public IAdvertisementRepository Advertisements { get; set; }
        public IProfileRepository Profiles { get; set; }
    }
}

而我的创业班是:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
         var builder = new ContainerBuilder();

        builder.RegisterType<Repositories>().As<IRepository>();
        builder.Register<IGraphClient>(context =>
        {
            var graphClient = new GraphClient(new Uri("http://localhost:7474/db/data"));
            graphClient.Connect();
            return graphClient;
        }).SingleInstance();
        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        //builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
       
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}
    

这是我的帐户管理员:

public class AccountController : ApiController
{
    private  IRepository _repository;
    private const string LocalLoginProvider = "Local";
    private ApplicationUserManager _userManager;
    private IGraphClient _graphClient;
   

    public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }       

    public AccountController(IRepository repository, IGraphClient graphClient,
         ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
    {
        
        AccessTokenFormat = accessTokenFormat;
        _repository = repository;
        _graphClient = graphClient;

    }
}

但我总是这个问题

"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

我在互联网上搜索,但找不到任何可以帮助的信息,有人可以指导我吗?

【问题讨论】:

    标签: asp.net-mvc dependency-injection asp.net-web-api2 autofac neo4jclient


    【解决方案1】:

    根据WebApi OWIN documentation

    OWIN 集成中的一个常见错误是使用GlobalConfiguration.Configuration在 OWIN 中,您从头开始创建配置。在使用 OWIN 集成时,您不应在任何地方引用 GlobalConfiguration.Configuration

    您似乎有几个问题:

    1. 使用 OWIN 时需要更新 HttpConfiguration
    2. 您缺少UseAutofacWebApi 虚拟方法调用。

    根据文档,您还需要 Autofac WebApi OWIN package

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
    
            // STANDARD WEB API SETUP:
    
            // Get your HttpConfiguration. In OWIN, you'll create one
            // rather than using GlobalConfiguration.
            var config = new HttpConfiguration();
    
            // Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
            // Run other optional steps, like registering filters,
            // per-controller-type services, etc., then set the dependency resolver
            // to be Autofac.
            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    
            // OWIN WEB API SETUP:
    
            // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
            // and finally the standard Web API middleware.
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
        }
    }
    

    【讨论】:

    • 我不需要 MVC 控制器我只需要上面提到的 web api 控制器,你知道吗?
    • 您也没有以正确的顺序注册全局过滤器。在拨打builder.Build(); 之前,您需要先拨打builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);。请参阅上面的示例。
    • 我按照你说的编辑了代码,结果和以前一样,你还有什么想法吗?
    • 非常感谢您的帮助我在stacktrace中有同样的错误芽我在autofac中没有任何问题,似乎问题出在其他部分,您能再帮我一次吗?我还安装了 Autofac Web Api Owin 包
    【解决方案2】:

    检查您的 Global.asax.cs。如果有,则应删除此行:

    GlobalConfiguration.Configure(WebApiConfig.Register);
    

    您可以像这样将其移至 Startup.cs 配置:

    WebApiConfig.Register(config);
    

    【讨论】:

      【解决方案3】:

      您还没有告诉 Autofac 如何创建 ISecureDataFormat&lt;AuthenticationTicket&gt; 实例。

      在您致电 builder.Build() 之前将其添加到您的启动课程中。

      builder.RegisterType<ISecureDataFormat<AuthenticationTicket>>().As<TicketDataFormat>();
      

      【讨论】:

      • 感谢您的帮助,但问题不在于您提到的问题,我尝试过但无法正常工作
      • 尝试发布一个可以实际运行的完整示例。否则它的任何人的猜测。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2013-07-01
      • 1970-01-01
      相关资源
      最近更新 更多