Does the MVC3 ever look for an implementation of I

2019-07-30 14:04发布

问题:

It's a pretty straight forward question. I'd like to be able to provide feedback to the user about the result of a postback using TempData (since it's auto-cleared). On successful execution of an action accepting a postback, I forward to a view dedicated to showing the result of the action, and would like to use TempData but leave SessionState disabled. For now the CookieTempDataProvider included in MVC3 Futures works great, but it doesn't seem like my implementation of IDependancyResolver is ever called to look for anything that implements ITempDataPovider.

Was this an oversight?

Anyone else tried this yet?

回答1:

Depenency injection is not used to look up instances of ITempDataProvider in MVC 3. The DI work done in MVC 3 was meant to expose the most frequently requested DI seems.

The only way to customize the instance of ITempDataProvider is to override the Controller.CreateTempDataProvider method.



回答2:

you can do this by creating a new controllerfactory which is requested by IDependancyResolver

/// <summary>
///   <para>Controller Factory</para>
/// </summary>
public class MyControllerFactory : DefaultControllerFactory {

    /// <summary>
    /// <para>Get instance of the controller</para>
    /// </summary>
    protected override IController GetControllerInstance(
            RequestContext requestContext, Type controllerType) {
        var controller = base.GetControllerInstance(requestContext, controllerType);

        if (controller != null
                && typeof(Controller).IsAssignableFrom(controller.GetType())) {
            // ITempDataProvider
            var tempDataProvider = DependencyResolver.Current
                                       .GetService<ITempDataProvider>();
            if (tempDataProvider != null)
                ((Controller) controller).TempDataProvider = tempDataProvider;
        }

        return controller;
    }
}

Then in your dependancy resolver set it to look for IControllerFactory, and return your ITempDataProvider

example for ninject:

_kernel.Bind<IControllerFactory>()
            .To<MyControllerFactory>().InSingletonScope();
_kernel.Bind<ITempDataProvider>()
            .ToMethod(c => new CookieTempDataProvider(HttpContext.Current))
            .InRequestScope();