Ninject and static classes - how to?

元气小坏坏 提交于 2019-12-01 16:27:53

Don't do it. Don't use a static class that needs dependencies of its own. This makes testing harder and other types that depend on this AuthenticationHelper won't be able to include it in their constructor which means they hide the fact that they depend on it.

Instead just do what you would always do: make AuthenticationHelper non-static, implement an IAuthenticationHelper interface on it and inject all dependencies through its public constructor.

But if you insist into keeping that class static (which again is a really bad idea), create a static Initialize(UserBusiness userBusiness) method on it, and call this method in the start-up path of your application. You can't let your DI container call this static method. They don't allow because 1. it's a bad idea, and 2. such static method only has to be called once, so letting your container auto-wire this for you doesn't really help.

As a side note, the lock is completely useless since you are locking access to a local variable "user" which will not change between the 2 "if (user == null)" lines.

Your intention is to lock access to the Context.Session[CURRENT_USER] element, so ..

            User user = (User)Context.Session[SessionKeys.CURRENT_USER];

            if (user == null)
            {
                lock (_lock)
                {
                    user = (User)Context.Session[SessionKeys.CURRENT_USER];
                    if (user == null)
                    {
                        user = _userBusiness.Find(CurrentUserId);
                        Context.Session[SessionKeys.CURRENT_USER] = user;
                    }
                }
            }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!