10

我正在使用 MVC3 和 Ninject 启动一个 Web 应用程序。在 Global.asax 文件中我还需要一个依赖项,它需要是一个单例。

我认为它应该是这样的:

public class MvcApplication : NinjectHttpApplication
{
    IUserAuthentication _auth;

    public MvcApplication()
    {
        base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
    }

    protected override IKernel CreateKernel()
    {
        var _kernel = new StandardKernel(new SecurityModule());
        _auth = _kernel.Get<IUserAuthentication>();

        return _kernel;
    }

    void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        _auth.ToString();
    }

但是后来我看到它在被调用_auth时为空MvcApplication_AuthenticateRequest

然后我尝试这样:

public class MvcApplication : NinjectHttpApplication
{
    ItUserAuthentication _auth;
    IKernel _kernel;

    public MvcApplication()
    {
        _kernel = new StandardKernel(new SecurityModule());
        _auth = _kernel.Get<IUserAuthentication>();
        base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
    }

    protected override IKernel CreateKernel()
    {
        return _kernel;
    }

    void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
    {
        _auth.ToString();
    }

但是现在我可以看到构造函数被多次调用,因此我将有几个 IKernel,我猜单例实例在我的应用程序范围内不会那么单例。

我该怎么做?使用静态变量?

4

4 回答 4

10

我们就是这样做的,我做了一些测试,我的 AuthService 似乎只进入了他的控制器一次:

public class MvcApplication : NinjectHttpApplication
    {

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected override IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());

            kernel.Bind<ISession>().To<MongoSession>().InRequestScope();
            kernel.Bind<IAuthenticationService>().To<AuthenticationService>().InSingletonScope();
            kernel.Bind<IMailer>().To<Mailer>().InRequestScope();
            kernel.Bind<IFileProvider>().To<MongoFileProvider>().InRequestScope();

            return kernel;
        }

        protected override void OnApplicationStarted()
        {
            base.OnApplicationStarted();

            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        var id = (FormsIdentity) HttpContext.Current.User.Identity;
                        var ticket = id.Ticket;
                        var authToken = ticket.UserData;
                        var authService = (IAuthenticationService)DependencyResolver.Current.GetService(typeof(IAuthenticationService));
                        var user = authService.GetUserForAuthToken(authToken);
                        if (user != null)
                        {
                            user.SetIdentity(HttpContext.Current.User.Identity);
                            HttpContext.Current.User = (IPrincipal) user;
                        }
                    }
                }
            }
        }
}

希望能帮助到你!

于 2011-04-13T00:59:41.650 回答
5

MVC 扩展默认注入 HttpApplication。但是只能使用属性注入!所以只需添加一个用 Inject 属性装饰的属性。

于 2011-04-01T14:48:05.910 回答
-1

将代码从构造函数移动到Application_Start方法。我相信即使创建了多个 HttpApplication 实例,Application_Start 也只会被调用一次,而且只在第一个实例上调用。让我知道它是否解决了您的问题。

这些是您可能在 Global.asax.cs 中拥有的各种事件处理程序:

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        InitializeComponent();
    }   

    protected void Application_Start(Object sender, EventArgs e)
    {

    }

    protected void Session_Start(Object sender, EventArgs e)
    {

    }

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {

    }

    protected void Application_EndRequest(Object sender, EventArgs e)
    {

    }

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {

    }

    protected void Application_Error(Object sender, EventArgs e)
    {

    }

    protected void Session_End(Object sender, EventArgs e)
    {

    }

    protected void Application_End(Object sender, EventArgs e)
    {

    }

    #region Web Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
    }
    #endregion
}
于 2011-04-01T11:13:03.320 回答
-1

你可以使用HttpApplication.Appliction属性吗?

public class MyHttpApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        this.Application["auth"] = GetAuthFromContainer();
    }

    protected void Application_AuthenticateRequest()
    {
        IUserAuthentication auth = (IUserAuthentication)this.Application["auth"]; 
        // auth != null
    }
}
于 2011-04-13T00:12:45.493 回答