Unity container in ASP.NET MVC - asp.net-mvc

I have a simple question. I'm newer with UnityContainer of Miscrosoft. I'm writing an ASP.NET MVC application with Unity for DI.
Have I a different CONTAINER for each user connected to my web app? Or the CONTAINER is the same for all users?
So if I resolve the life time of an object with ContainerControlledLifetimeManager does it mean that only for one user session this object is always the same?
I hope you understand.
Thanks,
Christian

Lifetime refers to the life of the object created by the DI process. Per request means each request gets its own object. If the object depends on the current user, querystring values on that request or values/presence of Request headers a PerRequest lifetime is appropriate. If you have settings that vary based on location of your service, for example, you saved values from web.config, then a the container is most likely created in global.asa and these objects can live as long as the container lives.
A concrete example:
You have a service as part of your site and you are migrating to vNext of that service. Users can opt-in by clicking a link that includes a parameter like &myService=vNext to see the new behavior. your Factory method uses the value of this parameter to select vNow or vNext for each request.
Here's some pseudo code to get you started:
container.RegisterInstance<IProductFactory>("enterprise", new EnterpriseProductFactory());
container.RegisterInstance<IProductFactory>("retail", new RetailProductFactory());
container.RegisterVersionedServiceFactory<IProductFactorySettings, IProductFactory>();
In this example RegisterVersionedServiceFactory is an extension method that does nothing but decide which of the IProductFactory instances to use for the current request. The factory provides the current instance (there are only two for the life of the service) to use for this request (thousands per seconds).
This pattern is what makes a very large site you probably used recently both very stable and very flexible. New versions of services are rolled out using this exact same pattern to help keep the site very stable.

Related

How to peek at message while dependencies are being built?

I building multitenancy into the unit of work for a set of services. I want to keep the tenancy question out of the way of day-to-day business domain work, and I do not want to touch every existing consumer in the system (I am retrofitting the multitenancy onto a system without any prior concept of a tenant).
Most messages in the system will be contexted by a tenant. However, there will be some infrastructure messages which will not be, particularly for the purpose of automating tenant creation. I need a way of determining whether to use a tenant-contexted unit of work, or a infrastructure unit of work uncontexted by a tenant because the way I interact with the database is different depending on whether I have tenant context. The unit of work is built in the process of spinning up the dependencies of the consumer.
As such I need a way of peeking at the message or its metadata before consuming it, and specifically, I need to be able to peek at it during the dependency building. I was intended to have a tag interface to mark tenant management messages out from normal business domain messages, but any form of identifying the difference could work. If I am in a unit of work resulting from an HTTP request, I can look at WebApi's HttpContext.Current and see the headers of the current request, etc. How do I do something analogous to this if I am in a unit of work resulting from messaging?
I see there is a way to intercept messages with BeforeConsumingMessage() but I need a way of correlating it to the current unit of work I am spinning up and I'm not seeing how that would work for me. Pseudocode for what I am trying to do:
if MessageContext.Message.GetType() = typeof<ITenantInfrastructureMessage>:
database = new Database(...)
else:
tenantId = MessageContext.Headers.TenantId;
database = new TenantDatabase(..., tenantId)
I am working in C#/.NET using MassTransit with RabbitMQ and Autofac with MassTransit's built-in support for both.
Your best option is to override at the IConsumerFactory<T> extension point, and extract the tenant from the message (either via a message header, or some message property) and register that in the container child lifetime scope so that subsequent resolutions from the actual consumer class (and it's dependencies) are properly matched to the tenant in the message.
In our systems, we have a TenantContext that is registered in a newly created LifetimeScope (we're using Autofac), after which we resolve the consume from the child scope, and the dependencies that use the tenant context get the proper value since it's registered as part of building the child container for the message scope.
It works extremely well, we even built up extension methods to make it easy for developers registering consumers to specify "tenant context providers" that go from a message type to the proper tenant id, which is used to build the TenantContext.
You can do similar things with activity factories in Courier routing slips (which are a specialization of a consumer).

ASP.NET caching startup values

I'm converting an application from C# WebForms to MVC.
The application gets settings from a centralized location using Web Services. These are settings you would typically find in a Web.Config, but the desire of the company is to store these values in a centralized location for all apps.
Currently, any time you request an application setting, it checks HttpContext.Cache to see if you've already retrieved the settings. If you haven't, it makes the web service call, and stores the settings (100+ objects that are essentially key/values) in the HttpContext.Cache. So the call to get application settings only occurs once.
Should I be looking at another way to do this? I was thinking the settings should just be a REST service call where you pass the key and get a value (the current service is an *.ashx which is really not ideal for exception handling amoung other reasons). But obviously this would result in more web requests. What is considered a best practice here? Is the current method fine and I should just leave the code working the same in the MVC app?
It is better to load all resources in one call:
fewer HTTP requests are better for performance. Http requests can have a latency around 50 ms thus it will take much longer to get all values one by one 50 x 100 = 5000 ms => 5 secs
if the external web service goes down then your application still works because you already downloaded and cached all values
I will keep the current solution if it works and focus on new things instead of rewriting a working code.

IIS instances sharing data

I don't know if this is common or something but I wanted to check. So I am building a site on an iis7 server and coming across a weird problem. Whenever I have 2 clients accessing the site it seems they are sharing info. Here is an example, when one client does a search for a particular item, the other client goes to the search page and see's the results of client's one search results. I am using a global class to store this information on my code behind.
So here is my question, my understanding of servers was that if two clients accessed the server they were running on different instances of the site, meaning that even if I have a global class in my code it would be as if two machines were running it. Am I wrong in this understanding?
Also are there settings in IIS that I need to change for this to work?
In asp.net, you can use Session variables which are unique serialized token type things stored in server memory. You can store html form info in these sessions so another page on your site can read it.
The syntax in your MVC controller action to create a Session would be:
Session["MyFormData"] = someObject;
http://msdn.microsoft.com/en-us/library/ms178581.aspx

How do I consume a real web service from a BPEL Process?

I've been doing some research on BPEL for about two weeks now and still don't quite get it.
I have deployed the HelloWorld sample in ODE and have also managed to deploy this other one.
My intention was to do something like the second example but with my own real WS deployed and working.
I'm now at the point of having a process with no errors and correctly deployed in ODE with the following structure:
I have started the project from a service definition importing my Multiply.wsdl. The Designer has composed the import tag into the MuktiplyProcessArtifacts.wsdl next to the PartnerLinkTypes all automagically so I assume all namespaces, etc are ok.
There is a few concepts I misundertand in order to make all of this work:
In my original Multiply.wsdl I have
soap:address
location="http://localhost:8080/WS-multiply/multiply"
but ODE tells me my soap:address must have the form host.port/ode/processes..
This doesn't sound reasonable to me since my WS could be implemented anywhere outside my ODE_HOME.
The second example I mentioned before explains how the Designer presumably creates a "Caller.wsdl", which in fact has the function I would desire, which is to implement a "wrapper" WSDL, providing the BPEL process with entry and exit points. The issue is the Designer does not generate that interface. Am I supposed to create it myself? Do I have to create it at all?
If that 3rd wsdl is really needed, is it the one I would have to call if I wanted to test the whole process?
It looks like your partner WSDL is associated to a myrole of a partnerlink. Partnerlinks and partnerlink types are a concept in BPEL that is used to define dual interfaces in a sense that if a partner A wants to communicate with a BPEL process as a buyer, it needs to provide a certain set of functionality that the process can use for further communications (i.e. sending a shipment confirmation to the buyer). Thus, a partnerlink maintains two roles, the myRole is the portType (aka interface) that the process itself provides, the partnerRole refers to a portType the process expects to be implemented by the partner. MyRoles must be of course implemented by the BPEL process and thus needs to have an endpoint that is exposed by the BPEL engine. PartnerRoles can be bound to arbitrary endpoints. This happens in the deployment descriptor, which is the deploy.xml in ODE.
I guess you can fix your process by assigning your partner WSDL to a partner role.
I hope http://thiliniishaka.blogspot.com/2012/10/develop-ws-bpel-process-using-wso2.html
and http://thiliniishaka.blogspot.com/2012/10/part-2-developing-ws-bpel-process-using.html may help you to resolve aforementioned queries.
Thanks
Thilini
Its mandatory to have Ode.war deployed at tomcat server, tomcat create a path like the picture, you need to config your endpoit with the complete path /ode/processes
c:\apache-tomcat-7.0.55\webapps\ode\WEB-INF\processes\BPEL_WS\

Authenticated user and multiple requests (IIS7 MVC3)

This is one of those questions that maybe should go so serverfault, but then maybe there is a code-level solution.
Anyway, here is the question. I have a regular MVC3 application which requires user login to access (uses the Authorize tag on most of the actions). I also have a Silverlight object within the application that makes HTTP GET calls to a controller action which returns an image (in fact this is a map tile). This particular controller action has no authorize tag, and is therefore public.
The Silverlight component runs slow or just blocks, because the MVC application can apparently process only ONE request at a time, as confirmed by firebug. This means that the map tiles can be served only one after the other. Moreover, regular (non-map-related) requests are enqueued too, and everything times out after a while.
So to make a test, I setup another website with the same document root, and I instructed the Silverlight component to read tiles from there. Now tiles ARE requested concurrently and it runs smoothly.
So, is there any way to resolve this situation and use one site only?
If you are using Session on the server action that would explain why requests are queued. Because the Session is not thread safe ASP.NET serializes all requests from the same session and executes them sequentially.

Resources