Sam
Sam

Reputation: 15770

Autofac - Inject ModelState into Service

I want to be able to inject model state into a service.

Service

public ThirdPartyService(IValidationDictionary dict)
{
    // IValidationDictionary, in this case is a ModelStateWrapper object 
    // I created to wrap model state
}

Registration

builder.Register(x => new ModelStateWrapper(x.Resolve<ControllerType>().ViewData.ModelState))
       .As<IValidationDictionary>().InstancePerHttpRequest();

Any ideas?

Upvotes: 2

Views: 414

Answers (1)

Mihalis Bagos
Mihalis Bagos

Reputation: 2510

This doesn't make sense as an InstancePerHttpRequest.

There can be a lot of controllers and there can be a lot of model states during a single Http request. Even if you access the current ControllerContext object through a refference in say, HttpContext.Current , the code you will produce is prone to bugs and malfunction due to design.

What I would suggest is to create an in-memory service-like repository to store all current ModelState and retrieve them by a controller-action key like (plain stupid example):

interface IHttpRequestModelStates
{
   ICollection<string, ModelState> ModelStates {get; set;}
   // you can retrieve Controller:Home / Index  model state 
   // using  ModelStates["HomeIndex"]
}

Upvotes: 2

Related Questions