Inject into asp.net web api model with autofac

蹲街弑〆低调 提交于 2019-12-25 03:00:13

问题


I want to use IValidatableObject.Validate() to check some aspects of my model against a repository before processing requests. However, with the config below _dalForValidation is never set in on Models.App, in other words the default empty constructor is always being called.

private static void ConfigureAutofac()
{
    var builder = new ContainerBuilder();
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    builder.RegisterType<DataAccessFacade>().As<IDataAccess>().InstancePerApiRequest();
    builder.RegisterType<Models.App>();
    var container = builder.Build();
    var resolver = new AutofacWebApiDependencyResolver(container);
    GlobalConfiguration.Configuration.DependencyResolver = resolver;
}

App has 2 constructors:

public App(IDataAccess dalForValidation)
{
    _dalForValidation = dalForValidation;
}

public App() {}

for completeness this is where I try to access it, getting a null reference exception:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var existingApps = _dalForValidation.FindApps().Convert<DB.App,App>();
    if (!ValidateProxyMappings(existingApps))
        yield return new ValidationResult("Invalid proxy mapping");
}

Perhaps the dependency resolver is not used for the model, or is there something else I'm missing here?

来源:https://stackoverflow.com/questions/13176973/inject-into-asp-net-web-api-model-with-autofac

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