NInject and thread-safety

Posted by cbp on Stack Overflow See other posts from Stack Overflow or by cbp
Published on 2010-05-31T06:27:41Z Indexed on 2010/05/31 6:32 UTC
Read the original article Hit count: 780

Filed under:
|

I am having problems with the following class in a multi-threaded environment:

public class Foo
{
    [Inject]
    public IBar InjectedBar { get; set; }
    public bool NonInjectedProp { get; set; }

    public void DoSomething()
    {
        /* The following line is causing a null-reference exception */
        InjectedBar.DoSomething();
    }

    public Foo(bool nonInjectedProp)
    {
         /* This line should inject the InjectedBar property */
         KernelContainer.Inject(this);
         NonInjectedProp = nonInjectedProp;
    }
}

This is a legacy class which is why I am using property rather than constructor injection.

Sometime when the DoSomething() is called the InjectedBar property is null. In a single-threaded application, everything runs fine.

How can this be occuring and how can I prevent it?

© Stack Overflow or respective owner

Related posts about multithreading

Related posts about ninject