Both have Request and Response properties, but I can't write a method that takes either HttpContext or HttpContextBase. In some places either one or the other is available so I need to handle both. I know HttpContextWrapper can convert in one direction, but still... why is it like this?
HttpContext has been around since .NET 1.0. Because of backward compatibility reasons, they can't change that class. HttpContextBase was introduced in ASP.NET MVC to allow for better testability because it makes it easier to mock/stub it.
This is an old question but I just had the same problem and the answer is in Gunder's comment.
Create you methods to use HttpContectBase and then wrap your context in a HttpContextWrapper when you want to call it from your code
public class SomeClass{
... other stuff in your class
public void MyMethod(HttpContextBase contextbase){
...all your other code
}
}
Usage
var objSomeClass = new SomeClass();
objSomeClass.MyMethod(new HttpContextWrapper(HttpContext.Current));
I think HttpContext.Current will be null if you make this call via ajax, I will investigate how to get the context and update this post.
Related
I'm not very experienced with Ninject, so I may have a concept completely wrong here, but this is what I want to do. I have a multi-tenant web application and would like to inject a different class object depending on what URL was used to come to my site.
Something along the lines of this, although maybe I can use .When() in the binding, but you get the idea:
private static void RegisterServices(IKernel kernel)
{
var currentTenant = TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower());
if (currentTenant.Foldername == "insideeu")
{ kernel.Bind<ICustomerRepository>().To<AXCustomerRepository>(); }
else
{ kernel.Bind<ICustomerRepository>().To<CustomerRepository>(); }
...
The problem is that HttpContext.Current is null at this point. So my question is how can I get the HttpContext data in NinjectWebCommon.RegisterServices. Any direction on where I might be going wrong with Ninject would be much appreciated as well.
Thank you
The problem is that your binding here resolves at compile time; whereas you need it to resolve at runtime, for every request. To do this, use ToMethod:
Bind<ICustomerRepository>().ToMethod(context =>
TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower()).Foldername == "insideeu"
? new AXCustomerRepository() : new CustomerRepository());
This means that, every time the ICustomerRepository is called for, NInject will run the method using the current HttpContext, and instantiate the appropriate implementation.
Note that you can also use Get to resolve to the type rather than to the specific constructor:
Bind<ICustomerRepository>().ToMethod(context =>
TenantLookup.LookupByDomain(HttpContext.Current.Request.Url.Host.ToLower())
.Foldername == "insideeu" ?
context.Kernel.Get<AXCustomerRepository>() : context.Kernel.Get<CustomerRepository>()
as ICustomerRepository);
I am following Steven Sanderson's Pro MVC2 book and have a question about using Ninject.
In the sports store example, we have in Global.asax.cs
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
and NinjectControllerFactory is defined as:
public class NinjectControllerFactory : DefaultControllerFactory
{
//A Ninject "kernet" is the thing that can supply object instances
private IKernel kernel = new StandardKernel(new SportsStoreServices());
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return (IController)kernel.Get(controllerType);
}
private class SportsStoreServices : NinjectModule
{
public string QString = null;
public override void Load()
{
Bind<IProductsRepository>().To<SqlProductsRepository>()
.WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString);
}
}
}
As you see the SqlProductsRepository is taking the connection string from the configuration file. If I need to make a decision here based on the URL query string parameters e.g. if param1=true I want to load from one repository versus the other, how can I do that? I have tried to see how to access query parameters in Load() method but I am not able to find a prepopulated place for that.
Also is Load() the right place to make a decision based on query parameters or should I somehow make this decision in Controller?
One would have multiple bindings that have .WithMetadata (or the special case thereof, are .Named()). Then, when resolving, you need to pass in a metadata filter and/or name parameter into the .Get<>() call to indicate the bindings. A small but of searching around here will yield examples, but by far the best source of ninject examples is the ninject tests, which are really clean and one of the reasons the ninject docs dont get the love they deserve (i.e. a v2 update).
i.e., you put a name or metadata filter in as an extra param into the:
return (IController)kernel.Get(controllerType, **here**);
As for best practice on how to manage this in more complex situations, I personally would go read Brand Wilson's set of posts on how they did it in MVC 3.
I guess it depends on your destination and aims:
making a sample do something while you learn - lash in the above
sort out DI based architecture to make you happy, run and buy Dependency Injection in .NET by Mark Seemann, strongly consider ASP.NET MVC 3 and read the Brad Wilson article series either way
a Module's Load() method only gets called when the application starts and the kernel is intialized. hence, there is no request context to make decisions on.
if it were me, I would inject both repositories into the controller and have the controller make the decisions on which to use. that way you can write unit tests to verify it's making the correct decisions.
I'm working with some WebForms/MVC-agnostic tools, and I need to get an instance of HttpContext given a reference to an HttpContextBase object. I can't use HttpContext.Current because I need this to work asynchronously as well (HttpContext.Current returns null during an asynchronous request). I'm aware of HttpContextWrapper, but goes the wrong way.
The simplest way is to get the application, ApplicationInstance, and use its Context property:
// httpContextBase is of type HttpContextBase
HttpContext context = httpContextBase.ApplicationInstance.Context;
(thanks to Ishmael Smyrnow who noted this in the comments)
Original answer:
You can, especially if the HttpContextBase instance you've been handed is of type HttpContextWrapper at run-time. The following example illustrates how you can do this. It supposes you have a method called Foo that accepts context as HttpContextBase but then needs to call a method in a third-party assembly (that you may not have the good fortune to modify) that is expecting the context to be typed as HttpContext.
void Foo(HttpContextBase context)
{
var app = (HttpApplication) context.GetService(typeof(HttpApplication));
ThirdParty.Bar.Baz(app.Context);
}
// Somewhere in assembly and namespace ThirdParty,
// in a class called Bar, there is Baz expecting HttpContext:
static void Baz(HttpContext context) { /* ... */ }
HttpContextBase has a method called GetService as a result of supporting IServiceProvider. The GetService override of HttpContextWrapper delegates to the GetService implementation of the wrapped HttpContext instance. The GetService implementation of HttpContext allows you to query for usual suspects like HttpApplication, HttpRequest, HttpResponse and so on. It just so happens that HttpApplication has a property called Context and which returns an instance of HttpContext. So one gets at the wrapped HttpContext instance by asking HttpContextBase for HttpApplication via GetService followed by reading the Context property of the returned HttpApplication instance.
Unlike HttpContextBase, GetService does not appear as a public member of HttpContext but that is because HttpContext implements IServiceProvider.GetService explicity while HttpContextBase doesn't.
Bear in mind that Foo is no longer testable because it relies on being able to unwrap the underlying HttpContext during testing and which is next to impossible to fake/stub in the first place. The point of this answer, however, is to address the question, “How do I get an HttpContext object from HttpContextBase?”, literally. The illustrated technique is useful in those situations where you find yourself sandwiched between components you don't necessarily have the luxury to modify.
You can,
var abstractContext = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);
You can't.
The whole purpose of HttpContextBase is to abstract away the dependency on the concrete HttpContext class. While it may contain a concrete HttpContext (such as is the case with httpContextWrapper), other implementations may have absolutely nothing to do with HttpContext.
Your best option is to define a custom Abstract Factory that can get a HttpContextBase for you, since you can always wrap a concrete HttpContext in a HttpContextWrapper.
var mockedService = new Mock<IService>();
mockedService.Setup(x => x.InterfaceMethod(args)).Returns(value);
_Service = mockedService.Object;
MyController controller =new MyController(_Service);
var result = (ViewResult)controller.Foo();
Now this Foo() Method contains the Following API Call
HttpContext.GetGlobalResourceObject(...,..);
But the HTTPContext is null, as i'm just unit testing , i have not Authenticated. and hence not populated the HTTPContext Object.
I cant set expectations on this class because the HTTPContext is sealed.
I've been searching in the net , but there were only samples to fake the HTTPContextBase
Now how do i get my Unit Test to Pass. Any Suggestions.?
thanks ,
vijay
The problem is you are not setting up an expectation for the "Centres" method. When you mock an object all implementations are replaced with a Noop until you specify otherwise using an Expectation.
I'm guessing you mocked GetValueFromResource rather than Centres because Centres calls GetValueFromResource. If this is the case, mocking GetValueFromResource is likely a superfluous fake and you don't need it.
Also, as has been pointed out on several other Moq posts, you'll need to make sure that you are not mocking what you are testing. If you are actually trying to test MyController, you'd want to mock any dependencies it has, but not MyController itself. This will cause you no end of confusion.
Edit
Based on this feedback it seems you have learned that your true problem is that you need to mock HTTPContext. Mocking HTTPContext is nontrivial. There are a few tools that can do it natively, like Type Mock, but the problem is that ambient context is not testable.
What you should be doing is requesting dependencies that give you the information you need while abstracting away their implementation. For example, in your case it seems like you are using HTTPContext to access resources. If you need something like this a good interface you could use would be:
public interface IResourceStore
{
object GetGlobalResource(string classKey, string resourceKey);
}
Your default implementation would use HTTPContext, but now you have an interface you can mock and have your MyController class use, rather than HTTPContext directly.
Mock<IResourceStore> resourceStore = new Mock<IResourceStore>();
//setup resourceStore expectations here
MyController testingTarget = new MyController(_Service, resourceStore.Object);
//target assertions here
Hope this helps.
Currently I have an ActionFilter that gets the current users name from HttpContext and passes it into the action which uses it on a service method. eg:
Service.DoSomething(userName);
I now have a reason to do this not at the action level but the controller constructor level. Currently I'm using structure map to create controllers and inject the service. I'm looking at something like:
public interface IUserProvider
{
string UserName { get; }
}
public class HttpContextUserProvider : IUserProvider
{
private HttpContext context;
public HttpContextUserProvider(HttpContext context)
{
this.context = context;
}
public string UserName
{
get
{
return context.User.Identity.Name;
}
}
}
That said, my IoC foo is really weak as this is the first project I've used it on.
So my question is... how can I tell structure map to pass in HttpContext in the constructor for HttpContextUserProvider? This just seems weird... I'm not sure how to think of HttpContext.
It sounds like you should be using HttpContextBase instead of HttpContextUserProvider. This is a out-of-box abstraction of HttpContext and allows you to create a mock, write UnitTests and inject your dependencies.
public class SomethingWithDependenciesOnContext
{
public SomethingWithDependenciesOnContext(HttpContextBase context) {
...
}
public string UserName
{
get {return context.User.Identity.Name;}
}
}
ObjectFactory.Initialize(x =>
x.For<HttpContextBase>()
.HybridHttpOrThreadLocalScoped()
.Use(() => new HttpContextWrapper(HttpContext.Current));
Have an interface abstract HttpContext.Current. Expose only the methods you need. GetUserName() would call HttpContext.Current.User.Identity.Name in the implementation, for example. Make that as thin as possible.
Take that abstraction and inject it into your other provider class. This will allow you to test the provider by mocking the http context abstraction. As a side benefit, you can do other nifty things with that HttpContext abstraction besides mock it. Reuse it, for one thing. Add generic type params to bags, etc.
I'm not sure why you're bothering. It seems like just using HttpContext.Current directly in HttpContextUserProvider is the right thing to do. You're never going to be substituting in a different HttpContext...
Maybe I left something out, but the above answer doesn't work for me (has since been deleted -- it was still a useful answer though -- it showed how to tell SM to pass constructor arguments). Instead if I do:
ObjectFactory.Initialize(x =>
{
x.BuildInstancesOf<HttpContext>()
.TheDefault.Is.ConstructedBy(() => HttpContext.Current);
x.ForRequestedType<IUserProvider>()
.TheDefault.Is.OfConcreteType<HttpContextUserProvider>();
});
I get it to work. I did this after finding: If you need something in StructureMap, but you can’t build it with new()…
Edit:
Thanks to Brad's answer I think I have a better handle on HttpContext. His answer definitely works, I just am not sure I like having the call to HttpContext.Current inside a class (it seems like it hides the dependency, but I'm far from an expert on this stuff).
The above code should work for injecting HttpContext as far as I can tell. Matt Hinze brings up the added that point that if all I need from HttpContext is the User.Identity.Name, my design should be explicit about that (having an Interface around HttpContext only exposing what I need). I think this is a good idea.
The thing is over lunch I kinda realized my service really only needs to depend on a string: userName. Having it depend on IUserProvider might not have much added value. So I know I don't want it to depend on HttpContext, and I do know all I need is a string (userName) -- I need to see if I can learn enough StructureMap foo to have make this connection for me. (sirrocoo's answer gives a hint on where to start but he deleted it :*( ).