Dependency Injection Of Model Repository - Is It A Singleton? - asp.net-mvc

My controllers now implement an interface and inject a repository implementation using the Unity framework. My question is, are these injected implementations singletons? Does that mean all of my users hitting the repository (from the controller) use the same instance?

It depends on whether you carry some ORM session along with your repository instance. If your repository is just a bunch of static methods than you shouldn't care and you can make it a singleton. Otherwise you want to preserve the state only within one web request so that other requests threads don't interfere with it.
Unity, unlike other IoC frameworks. doesn't come with singleton per web request lifetime manager, but you can easily implement it, see here for instance:
Singleton Per Call Context (Web Request) in Unity

No, do not make repositories singleton, special in a web application.
The controller factory create the repository (using Unity) and inject them in the controller.

Taken from the MSDN Unity docs...
The lifetime of the object it builds will correspond to the lifetime you specify in the parameters of the method. If you do not specify a value for the lifetime, the type is registered for a transient lifetime, which means that a new instance will be created on each call to Resolve...
Include an instance of the ContainerControlledLifetimeManager class in the parameters to the RegisterType method to instruct the container to register a singleton mapping.
So basically, the injection is transient unless you specify it as a singleton.

Related

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).

ZF2 Injecting a service to all the services by default

I have an authentication_service, which is required in all the services throughout the application. So, I don't want to inject this service every time (DRY). Is there a way, I can have this common service accessible from all the modules, with injecting via factory?
Thanks!!
You can use service initializers, great article with examples and more important with explained consequences:
http://www.masterzendframework.com/zend-framework/easy-setter-injection-in-zend-framework-2
I suggest you create a base service which defines all the common service requirements, such as your $authService property and the constructor that sets it. Then have your services extend that. Avoid reimplementing the constructor and property in every service to stay DRY, but injecting it via every service's factory is expected.

What is the cost of injecting a service that is never used into a controller in grails application?

What actually happens when we do def someService? Does the service code get linked to the controller code?
Grails uses spring IOC, your controllers and services are managed as spring beans, when you define a service inside a controller, spring will inject the service inside the controller, code does not get linked in anyway, just reference to service will be set. Though its not a much expensive operation, you would not want to define service dependencies that are not used to keep the code clean
I think under the hood it's the same process as Spring's #Autowired annotation, so you pay a bit of a performance penalty on start up but I don't think it's significant.
There's another stackoverflow question on the subject here.
Does the service code get linked to the controller code?
That does not make sense.
Actually services in grails are singleton by default.So if you inject a Service by def serviceName it wont create a new service object but a reference to same old service object.
So its not expensive of course.
But if in a service there is a property static session="prototype" or some non-singleton like this.Then it is expensive .

How do I get Unity to inject a reference to HttpSessionState to a service

Disclaimer: I have a fair bit of experience with DI containers but am quite new to Unity.
I have an MVC project that is all wired up with Unity DI using constructor injection and works great. But I now have a service that I want to inject into my controllers (and maybe places other than controllers at some point) and this service needs access to ASP.NET session state. The service's purpose is to manage a list in session and I don't want the list mechanics in my controller.
I realize I could add a Setup method to the service (and it's interface) that my controller could call, passing in a reference to the Session, before using the service, but I don't like that as I may want to make an implementation of the service that uses something other than Session for my state management and also it is implementation specifics leaking into my interface. I also realize I can use HttpContext.Current in my service but I don't want to do that for many reasons, particularly for the issues it creates for unit testing.
Can Unity inject a reference to HttpSessionState into the service's constructor?
There's a couple ways to do this. The easiest is probably to use an injection factory:
container.RegisterType<HttpSessionState>(
new InjectionFactory(c => { return HttpContext.Current.Session; }));
Then anywhere you have a dependency on the HttpSessionState in the graph, the delegate given will run and pull it out of HttpContext.Current.
Of course, this only works if you're doing a new resolve per request.

Can I access model information within the Initialize method of a controller?

In my controller I would like to set up the following services:
private IAccountService _accountService;
private IDataSourceService _dataSourceService;
private IProductService _productService;
private ISequenceService _sequenceService;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
}
However setting these up requires that I know the value of a property in the model that comes from the views and specifies dataSourceID.
In the Initialize method of a controller is the model information available? If the answer is no the are session variables available for me to check?
I'm not sure why you would want do that. The controller should not be in charge of configuring it's dependencies. You should use a Inversion of Control (aka Dependency injection) container to inject all dependencies in the constructor.
If your services require model specific information on construction I strongly suggest you review your architecture because that should not be the case. Most likely it's best to either pass that information in a method call (method injection) or abstract the dependency into a service.
In case you need information that is stored in a session, you could also consider wrapping the session in a service. You could then inject the session service as a dependency. This will also make it much easier to unit-test your controllers.
Do not hack internal workings of MVC framework. It seems to me that what do you want to do is in fact inversion of control, or dependency injection. It is well supported in MVC, you just need to make constructor of your controller accepting these services (as interfaces) and setup IoC container (MVC3 has built-in DependencyResolver compatible with all major IoC containers - I personally like Ninject). There are many tutorials on this, and for example Ninject can be set up fully automatically via nuget.

Resources