InstancePerLifeTimeScope and the life time of the objects - autofac

I am very new to Autofac dependency injection and I got these questions related to my project. I have gone through many articles but I am not getting a clear picture on some of the questions I have. Mine is a service application on .Net REST API. I am doing instance registration in App_Start module as shown below.
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<DCLMessengerContext>()
.As<DbContext>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<DbFactory>()
.As<IDbFactory>()
.ExternallyOwned()
.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(EntityBaseRepository<>))
.As(typeof(IEntityBaseRepository<>))
.InstancePerLifetimeScope();
builder.RegisterType<PersonServiceClient>()
.As<IPerfService>()
.InstancePerLifetimeScope();
builder.RegisterType<PagingServiceContractClient>()
.As<PagingServiceContract>()
.InstancePerLifetimeScope();
builder.RegisterType<MessageService>()
.As<IMessageService>()
.InstancePerLifetimeScope();
Container = builder.Build();
return Container;
}
My service layer is "MessageService" and there I am performing all the DB and other integration operations and getting the instances through constructor injection. These are the questions I have around this implementation.
I am using InstancePerLifeTimeScope for all my registrations. Is this is the right approach? After the life cycle of each controller request (http request), will these instances will be automatically disposed?
Do we need to manually implement any Dispose operation on any of these instances? ( I don’t have any unmanaged objects in my code)
From the service method, I need to create a fire&forget thread as well using Task.Run(). What is the best approach to supply instances to this fire&forget thread? If I use InstancePerLifeTimeScope, I can see that new thread also getting the same instances that available through the service class so I am just confused when these instances will be disposed?

When you resolve the instance per lifetime scope component, you get a
single instance per nested scope
So if you are using them in controllers. You will have one object for per request and they will be disposed. But if you resolve them in a singleton object they wil live with this object.
Is this is the right approach?
It depends what you need. If you need singleton object, it's not. If you just want to use this service in request scope use instanceperrequest it's better.
Autofac automatically calls dispose for IDisposable objects. If you
need dispose method, implement it. It's not related with autofac.
If you use another thread resolve objects in this thread. Otherwise when request disposed your objects will be disposed and your thread will be fail. Check this.

Related

ApplicationScope and REST calls

I have a project where the client (a Java stateful bean) will make a REST call to another bean (let's call it RequestBean) to perform a function and return a Response. Part of that function requires a call to a vendor's SOAP service. That service is a little slow to initialize in Java, but once initialized, then of course the calls are much faster.
I've been advised that I can move that service initialization to a separate ApplicationScoped bean (let's call it ServiceBean) so that it can initialize once and that's it. My question is about RequestBean. Should that be stateless, and how would it access the service that was initialized in ServiceBean?
I think I've figured this out. I added #Startup #Singleton to the service bean, as well as a method to pass the service reference to the request bean. This works. I'm not sure if this is really the proper way to do this, but for my immediate testing, it's sufficient.

Is Database Context shared between sessions in Entity Framework?

In Startup.cs it's possible to control dependency injection lifecycle using transients and singletons. However it's unclear how the lifecycle works when using .AddDBContext like so services.AddDbContext<DatabaseContext>(...);
Each controller uses this dependency by initialising it only once in the constructor and is reused throughout by the controller functions.
Is the context initialised for each request or is there a possibility this context being shared between user sessions resulting in bad state?
Note: duplicate question does not address if context is being shared between user sessions.
services.AddDbContext<>(...); registers your DbContext with Scoped lifetime. That means a new instance is created for every single request. No need to worry it would be shared with other connections.

Create a variable/object/resource that is accessible through entire application in ZF2

To be specific, I need to create an array variable that will be used for caching data, but I don't want to use ZF2 Cache Adapter.
I've tried to create a invokable class that would be used to instantiate object of my class that contains methods for setting and getting values from array that is also defined as a property of that class. As far as I understand, service manager treats all services as shared by default, which is supposed to create only one instance off my class when I get the service by service manager method get for the first time. But this doesn't work, if I get that service in different actions in my Controller class, which is what I need to do. So, how am I supposed to achieve this effect? Create an object that is available application-wide?
I had this kind of problem with managing a cart.
My cart is modeled by a CartManager, which is a unique instance for a user (session) and until paiement (cart is persisted in database).
I register my CartManager as a Service to build the first instance, this instance is built during an event handler attached on MvcEvent::EVENT_ROUTE, once built I override the CartManager service with my Instance, this way wherever I call the service, my first instance is served.
Then I persist (session or database) my Instance in an other event handler attached on MvcEvent::EVENT_FINISH.
All the event handlers are attached in Module::onBoostrap()

StructureMap - check if instance of some class/interface has been already created

I have the need to check if an instance of some interface has already been created by structuremap. I have tried ObjectFactory.GetInstance() but this creates a new instance of T when called and a concrete instance of T does not exist. I just want to check if an instance of T has already been created (not to create a new). I need this to force the creation of instances through a certain class).
You should be able to do this using:
ObjectFactory.Model.InstancesOf<IYourInterface>().First().ObjectHasBeenCreated();
Note, this only works for instances with Singleton, HttpContext or Hybrid lifecycle.
You cannot ask StructureMap if it has already created an instance of an interface.
However, it does have many lifecycle management features that allow it to control whether it creates a new instance, or returns a cached instance that it previously created.
You can tell StructureMap to make an instance HttpContextScoped, so that it returns the same instance for a given HTTP request.
It sounds like what you really want to know is how to handle NHibernate sessions in a web application with StructureMap. Try:
http://trason.net/journal/2009/10/7/bootstrapping-nhibernate-with-structuremap.html

Cross-Activity references using GWT with Gin

I have a GWT MVP application using Activities and Places. This is inspired by Mauro Bertapelle's sample (in this thread), apparently based on some of Thomas Broyer's work.
Here's the problem: I have LoginActivity make an RPC call, which for a successful login, returns a User. This user has a role (e.g., admin, regular user, guest). Several Views and Activities, including a NavigatorView, depend on this role for what they show or do. How do I get this User instance to the other Activities?
I do not have a ClientFactory; injection (Gin) is used for instantiating the Views in the ActivityProviders which provide my Activities/Presenters, and the ActivityProviders are injected into my ActivityMapper. So this may reduce to a Gin question: how do I get the user reference where it's needed? This seems to be similar to this SO question about global references in MVP.
Consider me a Gin newbie, this is my first attempt at using it. I'm guessing there is a "Gin way" to make this happen, but I don't know Gin well enough to know the best way to do this (if Gin should be used at all).
Much thanks.
Edit 1: Despite my best efforts searching SO for a similar question, I just found this question which is pretty much identical to mine (is the SO algorithm for finding "Related" links better than the search?). I'm thinking that the Gin answer by David is on the right track.
I don't think that an EventBus solution is possible. I'm following the Google guidelines which involve instantiating Activity at every Place change, so a single Event by itself will not suffice.
Something that I'm using on the server-side with Guice, and would work just as well on the client-side, is to bind to a custom Provider. In your case though, you'd have to make the provider a singleton and push the value into it from your RPC callback (rather than pulling it from some context).
You'd first need a specific provider:
#Singleton
public class CurrentUserProvider implements Provider<User> {
private User currentUser;
public User get() { return currentUser; }
public void setCurrentValue(User currentUser) {
this.currentUser = currentUser;
}
}
You'd bind User to the provider: bind(User.class).toProvider(CurrentUserProvider.class)
In your RPC callback you'd inject a CurrentUserProvider so you can setCurrentValue but everywhere else you'd inject Provider<User> to keep CurrentUserProvider as an implementation detail. For very short-lived objects, you could directly inject a User value rather than a Provider<User>.
If you need to notify objects of the value change, you could dispatch an event on the global event bus.
Alternately, you could always use the concrete CurrentUserProvider type (which wouldn't have to implement Provider anymore) and possibly make it a HasValueChangeHandlers so you could register listeners on it rather than on the event bus (but you'd have to clean-up after yourself in your activities' onStop and onCancel to avoid memory leaks, whereas it's taken care of automatically if you register handlers on the event bus in onStart).
(if you ask me, I'd rather go away with authenticating from within the app whenever possible)
I had similar requirements on a recent project.
When I get a reply from login (or logout) RPC I send a custom AuthenticationEvent on EventBus. All activities that are interested in this listen for this event. AuthenticationEvent has a reference to AppUser object which is null if user just logged out. AppUser contains all necessary data (privileges, groups, etc..) so that activities can inspect it and act upon it.
About global references: you can have a class with static methods providing data that you need. This class internally holds singleton references to needed instances. In my example I have static method AppUtils.getCurrentUser(). Internally it holds a reference to AppUser and also listens to AuthenticationEvent to set/reset this field.
As a side note: don't rely on client side to enforce access restrictions - you should separate your RPC servlets into two groups: public and private. Public can be accessed by anybody (this is basically login/logout RPC and some other public info RPC), while private RPC requires user to be authenticated. Access restrictions can be set per path/servlet: http://code.google.com/appengine/docs/java/config/webxml.html#Security_and_Authentication
Update:
As you noted, class with static methods is not advisable in this setup, because it is not replaceable and this prevents testing (which is the whole point of using GIN).
The solution is to inject a utility class holding globals (AppUtils) into activities that need the globals. AppUtils should be declared singleton in GIN configuration as one instance is enough for the whole app.
To use Provider or not is just a question if you want to delay the initialization of dependencies (AppUtil is dependency). Since AppUtils is a singleton for the whole app it makes no sense to have it lazy initialized.
Sometimes you will have a situation where you have multiple Activities shown on screen (in my case it was MenuBar and InfoBar). In this case, when user logs in you will need a way to notify them of the change. Use EventBus.