Showing posts with label lifestyle. Show all posts
Showing posts with label lifestyle. Show all posts

SignalR OnDisconnected Task and Dependency Injection with Castle Windsor - Hybrid lifestyle to the rescue

Today I faced a Castle Windsor dependency injection problem in an ASP.NET MVC app. The problem happened when using SignalR.

While implementing some UI real time user interaction I needed to have my persistence facility (Database context) injected inside my SignalR Hub class.

I Googled and found this awesome and to the point post by Mira Javora:

SignalR-Dependency Injection using Castle.Windsor

With the code he provided I was able to configure SignalR’s dependency resolver and everything was working as expected as Mira showed in his post.

In my case two objects are being injected in the Hub class:

public class AssessmentHub : Hub
{
    private MyContext _database { get; set; }

    private ILogger _logger { get; set; }

    public AssessmentHub(MyContext database, ILogger logger)
    {
        _database = database;
        _logger = logger;
    }

...
}

They were being properly injected in my own Hub class methods but things started to go wrong when SignalR’s OnDisconnected method was being called:

public override Task OnDisconnected()
{
    try
    {
        Guid connectionId = Guid.Parse(Context.ConnectionId);
// Database was null here! Sad smile
var client = Database.HubConnections.Single(hc => hc.ConnectionId == connectionId); UnlockChapterAndUpdateClients(client); Database.HubConnections.Remove(client); Database.SaveChanges(); } catch (Exception ex) { Logger.Error(ex.Message, ex); } return base.OnDisconnected(); }

This was the error I was getting:

HttpContext.Current is null. PerWebRequestLifestyle can only be used in ASP.Net.

The OnDisconnected method is an asynchronous method and as such it runs under a background thread ( not the one processing the request ). ASP.NET controls the threads and makes sure that only one thread is processing the request. This way HttpContext and as a consequence my _database injected object is null inside that method.

After some thinkering I remembered that I had my Persistence Facility registered PerWebRequest:

public class PersistenceFacility : AbstractFacility
{
    protected override void Init()
    {
        Kernel.Register(Component.For<MyContext>().          
            LifeStyle.PerWebRequest);
    }
}

Then, I Googled a little bit more and found this StackOverflow question:

Castle.Windsor lifestyle depending on context?

User Cuong Le shared a great post by Mauricio Scheffer called:

Hybrid lifestyles in Windsor

His post describes exactly what I needed (an Hybrid lifestyle ), that is, a way of keeping using the PerWebRequest life style when HttpContext is available but then resort to Transient lifestyle when it’s not.

An hybrid lifestyle is one that actually blends two underlying lifestyles: a main lifestyle and a secondary lifestyle. The hybrid lifestyle first tries to use the main lifestyle; if it's unavailable for some reason, it uses the secondary lifestyle. This is commonly used with PerWebRequest as the main lifestyle: if the HTTP context is available, it's used as the scope for the component instance; otherwise the secondary lifestyle is used.

I then grabbed Mauricio’s NuGet package Castle.Windsor.Lifestyles and changed my Persistence Facility code to:

public class PersistenceFacility : AbstractFacility
{
    protected override void Init()
    {
        Kernel.Register(Component.For<MyContext>().          
            LifeStyle.HybridPerWebRequestTransient());
    }
}

I’m back in business now. Call me

Why is it so important to Move Your Body?

Permit me to go a little bit "off topic" with this post… is it really off topic to a computer professional?

I know this is kinda of cliché and that it may scares you, but physical activity is a human necessity and as such it deserves special attention. So here I am writing about it hoping that someone that reads this takes notice and start acting right away. Do not leave for tomorrow what you can do today! Yet another cliché I know but it is perfect in this phrase.

People of my "professional class" and also from my generation also known as generation Y are the ones most impacted by the lack of physical exercises in this modern age of ours. In our age we are completely immersed in technology with products that make us want to avoid the outsides. Just to name a few: computers, internet, video games, delivery services, etc.

One thing that I as a computer engineer "have done" in the past 7 to 8 years was not moving my body to the extent needed.

When I was a kid ( 6 to 11 years old ) I used to play soccer almost 7 days a week. I lived near a soccer field. Then I moved to Volta Redonda where I live now and it ceased to happen.

In Volta Redonda I used to go to school every day cycling, that was about 6 KM (this route in Google Maps) each day. I used to play soccer with my street friends in front of my house (this green field seen in Google Street View) at least once a week, but as we all grew up we just did not keep contact and then the soccer games disappeared. I also used to go to Águas Quentes Country Club Resort "near" my house that has a lot of pools to practice swimming and that is now just past as well. I am not a member of the club anymore.

People that work with computers pass a lot of time fixed in a single place (programmers do it more frequently) as is my case and this tends to cause bad consequences to the body. Lots and lots of articles and TV programs debate this theme and lots and lots of people just do not give the necessary attention to this subject.

I am writing about this because I think it is crucial to our lives, that is, we were made to be in constant movement and it makes sense to expose my point of view since I am an avid user of computers and everything in between. Maybe this post will even serve as a start point to someone studying the impact of modern life in human health. What does a generation Y guy think about the subject? So here it is…

I definitely started to pay attention to this only after almost 2 years working at Chemtech. The work rhythm is intense and for someone that is starting in the job market, exercising can be a point of no interest and if you do not wake up to reality things can get worrisome. We had gymnastics at the workplace but that was not really something that I would call exercising, you know. While at Chemtech, on the weekends I was always inclined to rest since I was tired of working the whole week.

Move Your BodyOK. What have I found? We need a way of moving our body, working out for at least 30 minutes a day. You can do the kind of exercise that is a best fit to you, but the thing is: do something to move your body. Do not tie yourself to the same routine each and every day - car/bus to workplace, seat, a little walking to have lunch, in a sitting position again and then car/bus to home.

Since I started college in 2003 my exercising level downgraded to unacceptable levels. To correct this, one thing that I started doing lately was going to the gym to stretch my muscles – 5 days a week – 1/1.5 hours a day.

I am in the 3rd month mark now and I am really satisfied with the results because my overall mood got better and now I know I am contributing to my body and health. Body, Mind and Soul must be in synchrony.

The benefits of physical exercising are numerous and if you want to know more about them, refer to this article.

If you can not go to the gym: go walking/cycling to your workplace, do stair climbing (avoid elevators), but definitely do something that puts your body in movement. Start slowly and then increase the pace. You will see that as times goes by it starts to be a part of your day and the day you do not exercise you feel something is wrong/missing. Your body will ask for it. Amazing, isn't it? This is only a part of what we need to keep a healthy life. Of course, what you eat will have great impact in your health. Exercising alone will not be sufficient. Watch out for your way of life.

I think the point is: we all know that these are difficult days and that arranging all this stuff seems daunting enough. We already have a bunch of things to do but what if we do not keep close attention to our body health? We will not have anything else to be preoccupied with because maybe we will not be able to do that bunch of things again without a capable body. Did you get the point? I hope so.

An advice from an intensive computer user to everyone out there that thinks that exercises are not important: exercises do make a difference in life even more if you are a computer professional that depends on computers to get things done. It is better to start early and to keep it a constant in your life. You will save yourself and your money from doctors, medicines, hospitals, etc., that is, while it is not a guarantee it is most probably that you will save yourself from suffering. You will get a better quality of life having fun along the way.

Shake Yourself! I am linking to a Yes song titled Owner of a Lonely Heart that passes the message.

Updated on 12/30/2013

I’ve quit the gym because after 2 to 3 years there things started to get boring. I prefer the outdoors and cycling is my favorite exercise. The feeling I get while pedaling is inexplicable.

StravaIf you happen to own a mobile device, there’s a great app to keep track of your activity be it running or bike riding. It’s called Strava.

Here’s my latest activity:

Complementary reading

Sitting is Making You Fat and Killing You by Phil Haack