Autofac Dependecy Injection Azure function SingleInstance - dependency-injection

I followed this links. https://dontcodetired.com/blog/post/Azure-Functions-Dependency-Injection-with-Autofac
Autofac Binding at Runtime
It worked fine. I want to know when azure function scales, object injected into azure function will be shared by all the instances of azure function. In this case object is NaiveInvestmentAllocator.
Let me know if you have any doubt. Also I actually implemented combination of two links. It is like factory pattern is used to get the object of instances from Autofac container. I can share the code if anyone want But I dont think that necessary.
My question is if I implemented first link, injected object is shared by all instances of same azure function or not?

Nope.
As Azure Functions scale, the other instances run on different VMs/Containers. Its similar to running your function app on different VMs/Containers manually.
If the requirement is to have a shared state across multiple function app instances, you should offload the state persistence to something like Redis, Table Storage, Blob Storage, etc.
For example, you can use Azure Cache for Redis for example and inject a client for the same into your service class.
If the intention is to save the number of open connections, note that the limit is per instance.

Related

Dependency injection - Instance Lifetime for .Net MVC 5 webapps - Unity Container

I'm trying to have a better understanding of the lifetime of objects in DI by the point of view of an webapp. I'm using Unity Container docs here.
Singleton
Singleton lifetime creates globally unique singleton. Any Unity
container tree (parent and all the children) is guaranteed to have
only one global singleton for the registered type.
Now, because I've read so many articles, I've come to understand that Singleton is a instance that is created once and used for the entire life of application. What does this mean having in mind that 2 users use my app in the same time(or not) from different PCs - does this mean that if this instance is a variable, it will be common for all users for the entire time my app is hosted on the server (or until app App Pool Recycle)?
In my app I use different services that are injected in the controllers constructor.
Will Singleton be suited for an instance of a log service, or a DbContext instance?
If I use it for a DbContext instance, and something get's modified in the my Db structure - this instance will update?
Per Container
Per Container lifetime allows a registration of an existing or
resolved object as a scoped singleton in the container it was created
or registered. In other words this instance is unique within the
container it was registered with. Child or parent containers could
have their own instances registered for the same contract.
Same case: If 2 users use my app in the same time and visit same Controller, does this mean that they share the same instance of a Per Container variable/service?
Hope these questions have some meaning and I don't simply overthink it. Thank you!

How do you avoid injecting global state when sharing dependencies in DI?

Imagine you inject a single database connection to a handful of service classes. They now share what's essentially a global mutable state. How do DI frameworks deal with this? Do they:
Freeze the dependency before injection?
Only share immutable objects?
Wrap each dependency in a decorator to only provide exactly what's dependent on?
I tried searching for this and am a bit surprised I didn't find much. Feel free to provide links.
Related: https://en.wikipedia.org/wiki/Principle_of_least_privilege
Most DI containers provide the feature of registering a dependency within a Lifetime. For instance in .net core DI you can register a service with three different lifetimes:
Singleton: There is only one single instance. All the consumers of that service will use that instance. If one consumer changes the state of that dependency, all the other consumers will see that change.
Scoped: There is one instance per scope, where a scope is a web request. If a consumer changes the state of a scoped service, all the other consumers that will run in the same web request will see the change.
Transient: Each consumer uses a different instance of the service.
Always in .net core, the DBContext is (by default) added as a scoped service, this means that in the same web request all the consumers will use the same instance and this is useful when you need to run a transaction across different consumers (or better across different repositories).

Azure Web Role apply https binding to multiple instances

I have two web roles scaled up to 4 instances and at least two instances are running at a time. The certificate requested by a user via first website is pushed to blob storage and creates a queue message for the other website to read it.
I have a while loop inside the Run method implementing RoleEntryPoint to check the message, upload the certificate to store if available, apply https binding, and delete the message.
The bindings are applied to current instance and not into both. Is there a way to I can access all instances and apply bindings to both at once? If not, what are some better approaches?

Call a method/ handle event in Windows Service from hosted WCF Service

apologies in advance for this question being dumb, or previously covered. I have researched far and wide but have not found any resources on WCF/ Windows Services that cover this question.
I have a managed Windows Service which is working nicely. Every n (>5) seconds it checks on the status (e.g. memory consumption) of some processes and other Windows services and also does some database logging and raises events where necessary.
I intend to make an ASP.NET website that would allow users to query the status of the processes that the Windows Service is monitoring. Having researched the options it looks like the up-to-date method would be to use a WCF Service, hosted in the Windows Service, to act as intermediary between the ASP.NET website and the Windows Service. Such that, a user could request through the browser a snapshot of the current status of whatever set of processes the Windows Service was monitoring, and have this request and subsequent response relayed through the WCF service (using named pipes, I think).
So, my difficulty is that there a set of methods and events in the Windows Service for which a single root object exists (let's say MonitorObject). I don't see how the ServiceHost can be instantiated with the reference to MonitorObject so that the WCF Service can call the methods in the Windows Service. I am thinking that perhaps I need to make the Monitor object a shared (I am VB'ing) member of the Windows Service class (that contains OnStart and OnStop) and make all the events shared so that the WCF Service can just access the WindowsService.SharedMonitorObject without needing to be passed the object....
However, I am lost in the subject and am seeking any advice on how best to proceed.
Thanks in advance.
I think you're going down the right track. I wouldn't necessarily make the entire MonitorObject shared, but you might put a shared method in that object that will return the single root object to the caller.
There is a design pattern called the Singleton Pattern that will help you with this. Jon Skeet has written an excellent article on some of the things to be aware of when using this pattern in .NET. His article uses C# for the examples, but here's a SO question referencing this pattern using VB.
While it's unclear from your description, my guess is that your Windows Service is essentially single-threaded right now. Just keep in mind that once you add the WCF service, you'll need to make the methods that it references thread-safe.

ASP.NET MVC consuming WCF

My ASP.NET MVC 2 controllers are currently instantiating service objects in their constructors by passing repository instances that are instantiated by Castle Windsor. I have unit tests that call the controller actions after passing Moq instances of the repositories to the controller's constructor.
I want to allow a third-party UI to access these service objects through WCF.
It occurred to me that converting my existing Service layer into Web services or even adding a new Web service layer between the UI and the existing Service layer will break my unit tests unless I find a way to bridge that gap.
I was trying to work out a solution where my UI was coded against an interface of the service layer (it already is) and I could use DI to pass the Web service implementation at run-time and pass the existing implementation during unit testing. The Web service implentation would simply call the existing implementation.
Questions:
Is such an approach advisable / possible?
Are there any examples of this in a tutorial or open source project?
EDIT:
I believe I have a workable solution now thanks to the suggestions below. I created a WCF Service Application that uses the existing service interfaces from my domain model. The WCF implementation is a class where the constructor takes repository instances from Ninject's WCF extension and creates an instance of the service from the domain model. Each method/function in WCF simply calls the same method/function from the existing service layer.
There were some caveats. For example, I can no longer pass a reference to my ASP.NET MVC ModelState when I create the service in the controller (actually, I use Ninject to create an instance of the WCF service and supply that to the controller's constructor). The reason is that WCF is a messaging platform - changes must be explicitly communicated back with each call (i.e. my validation errors are now communicated back as reference parameters on individual functions/methods).
I also had to add some serialization/servicemodel references to my formerly POCO Core project.
Also, I switched from Castle to Ninject because Castle's WCF solution has a maturity level of low and I wasn't comfortable using that at this time.
Can you explain in more detail why your tests would break?
I do this type of development all the time. Services as classes => services as WCF services.
Your tests shouldn't break. A WCF Service is almost 100% contract, the underlying business code and logic shouldn't have to change.
Check out the Web Services Software Factory created by the Patterns & Practices team. It is a good way to structure your services into contract projects (data, message, service) and "business code". Once you get a better understanding of how to structure your code, you can refactor their style to something that fits you a little better. Their example tends to separate everything into lots of VS projects, which can be a little overkill for most shops. Example, I don't see many shops sharing data contracts across projects. Yes, in a perfect world, you should probably share a lot os types (like address) across projects, but I don't see it done very often. So, I tend put all my contract stuff in one VS project.
If your services are already defined as interfaces then you've got a head start.
Pass the services into the controllers as constructor dependencies, rather than the repositories. Let your DI container A) provide the repositories to the services, and B) provide the services to the controllers.
If you want to stand up your service layer as wcf services to be accessed by other applications, you'll want to use the wcf service factory to pull the concrete service implementations out of your DI container. Here's an example with windsor, it should be easy to adapt to whatever container you use.
At this point you can modify your website to either A) continue to invoke the services directly, or B) have them call back to the web services using service clients. There are pros and cons to both methods.

Resources