Does the MVC3 ever look for an implementation of I

2019-07-30 13:10发布

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?

2条回答
Bombasti
2楼-- · 2019-07-30 13:45

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();
查看更多
可以哭但决不认输i
3楼-- · 2019-07-30 13:50

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.

查看更多
登录 后发表回答