问题
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