如何摆脱Autofac错误?

时间:2014-09-12 11:33:18

标签: dependency-injection autofac

我们使用Autofac的ASP.NET应用程序。出现以下错误:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'ConcertRu.ApplicationsCore.Services.SessionWebAppService' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.Web.HttpContext httpContext' of constructor 'Void .ctor(System.Web.HttpContext)'.
Cannot resolve parameter 'System.Web.HttpContextBase httpContext' of constructor 'Void .ctor(System.Web.HttpContextBase)'.
Cannot resolve parameter 'ConcertRu.Infrastructure.Contracts.IConcertHttpContext httpContext' of constructor 'Void .ctor(ConcertRu.Model.Contracts.IConcertDb, ConcertRu.Infrastructure.Contracts.IConcertHttpContext)'.

的Global.asax.cs:

// Create the container builder.
var builder = new ContainerBuilder();

// Register the Web API controllers.
builder.RegisterControllers(Assembly.GetExecutingAssembly());

// Register other dependencies.
var services = typeof(AccessTokenService).Assembly;
builder.Register(c => ConcertDb.Current).As<IConcertDb>().SingleInstance();
builder.RegisterAssemblyTypes(services)
        .Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces()
        .SingleInstance();

// Build the container.
var container = builder.Build();

// Create the depenedency resolver.
var resolver = new AutofacDependencyResolver(container);

// Configure Web API with the dependency resolver.
DependencyResolver.SetResolver(resolver);

SessionWebAppService类:

public class SessionWebAppService : WebAppServiceBase, ISessionWebAppService
{
    public SessionWebAppService(HttpContext httpContext)
        : this(new ConcertDb(), new WebFormContext(httpContext))
    {
    }

    public SessionWebAppService(HttpContextBase httpContext)
        : this(new ConcertDb(), new MvcContext(httpContext))
    {
    }

    public SessionWebAppService(IConcertDb concertDb, IConcertHttpContext httpContext)
        : base(concertDb, httpContext)
    {
    }

    ...
}

WebAppServiceBase类:

public abstract class WebAppServiceBase : ModelServiceBase
{
    private readonly IConcertHttpContext _httpContext;

    protected WebAppServiceBase(IConcertDb concertDb, IConcertHttpContext httpContext) : base(concertDb)
    {
        _httpContext = httpContext;
    }

    ...
}

1 个答案:

答案 0 :(得分:1)

Autofac非常明确地指出了什么是错误的:HttpContextHttpContextBaseIConcertHttpContext都无法从容器中解析出来。看到您的注册码,这是有道理的,因为只有控制器,您的IConcertDb服务已注册。