Ninject. Optional Injection - c#

I have global flags which enable/disable features. I'd like to inject some dependencies depending on some flag. Some features require classes which are heavily constructed so I want to inject null if the value of the flag is false and the actual dependency otherwise. Ninject doesn't allow injecting null. Are there any other options?
Update: constructor arguments can be decorated with OptionalAttribute attribute. In this case null is injected if there is no corresponding binding found. There is a problem here: I can't verify if target class can be properly constructed. I have a test for each public dependency which verifies if it can be constructed successfully. In case if the value of the flag is true I will not be able to find the error when the dependency decorated with the OptionalAttribute attribute, cannot be constructed properly. I'd like to manage it on binding level only.

You can vary the injection behaviour by binding using a factory method (i.e. ToMethod), and it's possible to allow injection of nulls by configuring the container's AllowNullInjection setting.
Another alternative would be to use a factory method and supply a lightweight dummy object instead of your heavy-weight class. If you are using interfaces this would be straightforward, just have implementations of the interface that do nothing. You could even use a mocking framework such as FakeItEasy to construct these dummies for you. The benefit here, is that the dummy makes the special behaviour transparent to clients i.e. clients do not need to check for null, etc.
An example of using a factory method, plus AllowNullInjection and nulls:
public void Configure()
{
bool create = true;
IKernel kernel = new StandardKernel();
kernel.Settings.AllowNullInjection = true;
kernel.Bind<IFoo>().ToMethod(ctx => create ? ctx.Kernel.Get<Foo>() : null);
DependendsOnIFoo depFoo = kernel.Get<DependendsOnIFoo>();
}
private interface IFoo {}
private class Foo : IFoo {}
private class DependendsOnIFoo
{
public DependendsOnIFoo(IFoo foo) {}
}
And an example where a lightweight object is substituted depending on the flag:
public void Configure()
{
bool heavy = true;
IKernel kernel = new StandardKernel();
kernel.Bind<IFoo>()
.ToMethod(ctx => heavy ? ctx.Kernel.Get<HeavyFoo>() : (IFoo)new DummyFoo());
DependendsOnIFoo depFoo = kernel.Get<DependendsOnIFoo>();
}
private interface IFoo {}
private class HeavyFoo : IFoo {}
private class DummyFoo : IFoo { }
private class DependendsOnIFoo
{
public DependendsOnIFoo(IFoo foo) {}
}

Injecting null is usually not a wise idea. This will pollute your code with checks if the object is null or not as shown by the following code:
public interface IFoo
{
void Do();
}
public class Foo : IFoo
{
public void Do()
{
DoSomething();
}
}
public class UglyNullCheckingBar
{
IFoo foo;
public Bar(IFoo foo)
{
this.foo = foo;
}
public void Do()
{
if (this.foo != null)
{
this.foo.Do();
}
}
}
The better way in this case is to implement a Null Object which does absolutely nothing and inject this one instead of null. This keeps your code clean.
public class NullFoo : IFoo
{
public void Do() {}
}
public class Bar
{
IFoo foo;
public Bar(IFoo foo)
{
this.foo = foo;
}
public void Do()
{
this.foo.Do();
}
}

Related

Register composite pattern in StructureMap

In my project I use composite pattern and I want to register and resolve this hierarchy using StructureMap.
The code looks like this
interface IFoo
{
void Do();
}
class Foo1 : IFoo
{
public void Do()
{
Console.WriteLine("Foo1");
}
}
class Foo2 : IFoo
{
public void Do()
{
Console.WriteLine("Foo2");
}
}
class CompositeFoo : IFoo
{
private readonly IEnumerable<IFoo> foos;
public CompositeFoo(IEnumerable<IFoo> foos)
{
this.foos = foos;
}
public void Do()
{
foreach (var foo in this.foos)
{
foo.Do();
}
}
}
class Bootstrapper
{
public static void Run()
{
var container = new Container(c =>
{
c.For<IFoo>().Add<Foo1>();
c.For<IFoo>().Add<Foo2>();
c.For<IFoo>().Use<CompositeFoo>();
});
// throws exception
var result = container.GetInstance<IFoo>();
result.Do();
}
}
The specified code throws this exception
Bi-directional dependency relationship detected!
Check the StructureMap stacktrace below:
1.) Instance of IFoo (CompositeFoo)
2.) All registered children for IEnumerable<IFoo>
3.) Instance of IEnumerable<IFoo>
4.) new CompositeFoo(*Default of IEnumerable<IFoo>*)
5.) CompositeFoo
6.) Instance of IFoo (CompositeFoo)
7.) Container.GetInstance<IFoo>()
I can not find anything related to this in the official documentation or anywhere on the internet. Is this at all possible without manually specifying all possible dependencies?
The way i see it you have a couple of options:
Register CompositeFoo as CompositeFoo and not IFoo. Then ask for an instance of CompositeFoo.
cfg.For<IFoo>().Add<Foo1>();
cfg.For<IFoo>().Add<Foo2>();
cfg.ForConcreteType<CompositeFoo>();
...
var result = container.GetInstance<CompositeFoo>();
Define a new interface for the composite.
interface ICompositeFoo : IFoo {}
class CompositeFoo : ICompositeFoo
...
cfg.For<IFoo>().Add<Foo1>();
cfg.For<IFoo>().Add<Foo2>();
cfg.For<ICompositeFoo>().Use<CompositeFoo>();
...
var foo = container.GetInstance<ICompositeFoo>();
After trying to accomplish this using policies or factory classes, I sacked StructureMap in favour of Grace. There I can easily instantiate the composite object with the following code
var container = new DependencyInjectionContainer();
container.Configure(c =>
{
c.Export<Foo1>().As<IFoo>();
c.Export<Foo2>().As<IFoo>();
c.Export<CompositeFoo>().As<IFoo>();
});
var foo = container.Locate<IFoo>();
foo.Do();
And the result is as expected:
foo1
foo2
The problem with StructureMap for me is that they do not support any way to specify dependencies for an object dynamically. I could make it work if I manually write all instances which should be injected or resolve all, including the composite object. I could probably make it somehow possible using policies with injected container and specify dependencies that way, but it is too hacky in my opinion.

StackOverflow exception when using Fallback with Create in LightInject 3.0.2.5

This is a copy of https://github.com/seesharper/LightInject/issues/173
I tried to automatically create concrete types using fallback and .Create() but it somehow loops itself and I don't understand why.
Here is my test code:
public class Foo
{
public Foo(IBar bar, IBar2 bar2)
{
}
}
public interface IBar2
{
}
class Bar2 : IBar2
{
}
public interface IBar
{
}
class Bar : IBar
{
}
private ServiceContainer container = new ServiceContainer();
container.RegisterFallback((t, s) => true, Factory);
container.Register<IBar, Bar>();
container.Register<IBar2, Bar2>();
var foo = container.GetInstance<Foo>(); // Error here
private object Factory(ServiceRequest req)
{
return container.Create(req.ServiceType);
}
Could you please advise?
It loops even if the Factory method looks like this:
private object Factory(ServiceRequest req)
{
container.Register(typeof(Foo));
return container.GetInstance<Foo>();
}
but works perfectly if I register Foo beforehand (which I obviously want to avoid)
container.Register(typeof(Foo));
var foo = container.GetInstance<Foo>(); //ok
I am the author of LightInject and the issue has been updated with a workaround that enables the container to resolve unregistered concrete classes.
https://github.com/seesharper/LightInject/issues/173
It's the bug that was confirmed in https://github.com/seesharper/LightInject/issues/173 and is looked after by author

moq only one method in a class

I'm using moq.dll
When I mock a class(all the IRepository interface) i use this line code
int state = 5;
var rep = new Mock<IRepository>();
rep.Setup(x => x.SaveState(state)).Returns(true);
IRepository repository = rep.Object;
but in this case i mock all the function in repository class.
Then all the methods in class repository are substituted with the methods setup of Mock dll
I want use all the methods defined in class repository(the real class) and mock only one function(SaveState)
How can I do this? Is possible?
You can create an instance of the real repository, then use the As<>() to obtain the desired interface, which you can then override with the setup, like this:
var mockRep = new Mock<RealRepository>(ctorArg1, ctorArg2, ...)
.As<IRepository>();
mockRep.Setup(x => x.SaveState(state)).Returns(true);
Then mockRep.Object as the repository dependency to the class under test.
Note that you will only be able to Mock methods on the Interface*, or virtual methods, in this way.
Update : *This might not work in all scenarios, since .Setup will only work on virtual methods, and C# interface implementations are "virtual" and sealed by default. And using As() will prevent the partial mock behaviour.
So it appears that the RealRepository concrete class will need to implement the IRepository interface with virtual methods in order for the partial mock to succeed, in which case CallBase can be used for the wire-up.
public interface IRepo
{
string Foo();
string Bar();
}
public class RealRepo : IRepo
{
public RealRepo(string p1, string p2) {Console.WriteLine("CTOR : {0} {1}", p1, p2); }
// ** These need to be virtual in order for the partial mock Setups
public virtual string Foo() { return "RealFoo"; }
public virtual string Bar() {return "RealBar"; }
}
public class Sut
{
private readonly IRepo _repo;
public Sut(IRepo repo) { _repo = repo; }
public void DoFooBar()
{
Console.WriteLine(_repo.Foo());
Console.WriteLine(_repo.Bar());
}
}
[TestFixture]
public class SomeFixture
{
[Test]
public void SomeTest()
{
var mockRepo = new Mock<RealRepo>("1st Param", "2nd Param");
// For the partially mocked methods
mockRepo.Setup(mr => mr.Foo())
.Returns("MockedFoo");
// To wireup the concrete class.
mockRepo.CallBase = true;
var sut = new Sut(mockRepo.Object);
sut.DoFooBar();
}
}
I came to this page because I had exactly the same problem: I needed to mock a single method, which was relying on many external sources and could produce one of three outputs, while letting the rest of the class do its work. Unfortunately the partial mock approach proposed above did not work. I really don't know why it did not work. However, the main problem is that you can't debug inside such mocked class even if you put break points where you want. This is not good because you might really need to debug something.
So, I used a much simpler solution: Declare all methods that you want to mock as virtual. Then inherit from that class and write one-liner mock overrides to return what you want, for example:
public class Repository
{
/// <summary>
/// Let's say that SaveState can return true / false OR throw some exception.
/// </summary>
public virtual bool SaveState(int state)
{
// Do some complicated stuff that you don't care about but want to mock.
var result = false;
return result;
}
public void DoSomething()
{
// Do something useful here and assign a state.
var state = 0;
var result = SaveState(state);
// Do something useful with the result here.
}
}
public class MockedRepositoryWithReturnFalse : Repository
{
public override bool SaveState(int state) => false;
}
public class MockedRepositoryWithReturnTrue : Repository
{
public override bool SaveState(int state) => true;
}
public class MockedRepositoryWithThrow : Repository
{
public override bool SaveState(int state) =>
throw new InvalidOperationException("Some invalid operation...");
}
That's all. You can then use your mocked repos during unit tests AND you can debug anything you need. You can even leave the protection level below public so that not to expose what you don't want to expose.

Ninject Interception 3.0 Interface proxy by method attributes

I have just upgraded a relatively large codebase from Ninject 2.2 to Ninject 3.0. Everything seems to be going as planned except I had to make a few changes to the interception stuff that we use.
interface IFoo
{
Bar GetBar();
}
class Foo : IFoo
{
[LogMethod(Level = LogLevel.Error)]
public virtual Bar GetBar()
{
return new Bar();
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
class LogMethodAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Kernel.Get<ILogMethodInterceptor>();
}
public LogLevel Level { get; set; }
}
interface ILogMethodInterceptor : IInterceptor { }
class LogMethodInterceptor : ILogMethodInterceptor
{
public void Intercept(IInvocation invocation)
{
LogMethodAttribute attr = (LogMethodAttribute)invocation.Request.Method.GetCustomAttributes(typeof(LogMethodAttribute), true).FirstOrDefault();
// Log something - using attribute properties
}
}
NinjectSettings settings = new NinjectSettings { LoadExtensions = false };
IKernel kernel = new StandardKernel(settings, new DynamicProxy2Module());
kernel.Bind<ILogMethodInterceptor>().To<LogMethodInterceptor>();
kernel.Bind<IFoo>().To<Foo>();
This cut-down version is what we used to great effect with Ninject 2.3. Because interface proxies were not allowed, we had all methods marked as virtual and that enabled the Castle dynamic proxy to override them.
Now I want to move the [LogMethod] to the interface level to use interface proxies:
However, when I move it, Ninject no longer detects that I want to intercept this class.
Also if I leave it as is, a subtler problem occurs:
The invocation.Request.Method is the MethodInfo from the Interface IFoo - not the implementation Foo, this means that I cannot retrieve my attribute any more. So I am stuck between these two issues for the moment - If I put the attribute in the interface, Ninject doesn't create the proxy, if I put the attribute in the implementation, I cannot easily retrieve my attribute to access it's properties. At the moment my only solution is this:
interface IFoo
{
[LogMethod(Level = LogLevel.Error)]
Bar GetBar();
}
class Foo : IFoo
{
[LogMethod(Level = LogLevel.Error)]
public virtual Bar GetBar()
{
return new Bar();
}
}
Or use the InterfaceMapping to convert my IFoo MethodInfo to the invocation.Request.Target.GetType() (which returns the implementation type - Foo) MethodInfo.
Any recommendations?

Using a class in its constructor C# - Does it smell?

Does the code below smell? I'm refactoring some code and have discovered this circular relationship where foo needs a class which needs an interface which foo itself implements.
In the real code, foo is a Silverlight UserControl and ifoo has methods to do UI type things like raise a dialog box (eg ShowMessage). The needsAnIfoo class is a (kind of) controller which uses the ifoo interface whenever it want's to do anything with the UI. I have different "themed" UI's which implement iFoo and have the same boiler plate code in their constructor. The needsAnIfoo has various properties which are databound to the UI (so it's kind of a model too.)
It compiles and runs fine, but I'm wondering if there's a better way.
So, does it smell?
interface ifoo
{
void bar();
}
class foo : ifoo
{
readonly needsAnIfoo _needsAnIfoo;
internal foo()
{
_needsAnIfoo = new needsAnIfoo(this);
}
#region ifoo Members
public void bar()
{
throw new NotImplementedException();
}
#endregion
}
class needsAnIfoo
{
readonly ifoo _myfoo;
public needsAnIfoo(ifoo foo)
{
_myfoo = foo;
}
}
static void Main(string[] args)
{
foo foo = new foo();
}
Perhaps I should new up the needsAnIfoo without passing the iFoo in the constructor and then give it the iFoo in an Initialize method. But this looks very odd:
foo foo = new foo();
needsAnIfoo needsAnIfoo = new needsAnIfoo(foo);
foo.Initialise(needsAnIfoo);
Sounds like a great place to institute a pattern, I'd say Factory Method.
class Factory
{
public:
virtual needsAnIfoo* Create(ProductId);
};
needsAnIfoo* Factory::Create(ProductId id)
{
if (id == TYPE1) return new needsAnIfoo(ifooType1());
if (id == TYPE2) return new needsAnIfoo(ifooType2());
...
return 0;
}
Then you would use it like so:
Factory f = new Factory();
theme1 = f.Create(TYPE1);
theme2 = f.Create(TYPE2);
Patterns are your friend!
It doesn't look right to me. Smells fragile.
Have you considered looking at either a builder or factory pattern to create the relevant objects and establish the relationships between them? It might provide a safer way forward.
I agree that a Builder or Factory pattern, or similar, would be better. The provided code is not very testable and is, as mentioned, kind of fragile, so some form of dependency injection would be good.
The pattern to use will depend how foo and needsAnIFoo use each other. You might need to consider the Observer pattern as well, if needsAnIFoo is a subject, foo is an observer, and bar() is an update method.
It sounds like this may be overly complicated, and that you are making your theme be a controller and have a controller (by having both classes implement ifoo)
You may get better results if you separate the concepts of theme and controller, so that the controller has a theme. Then, for example, when the controller does something, like pop up a dialog, it looks into its theme to find out what font to use.
Like this:
interface itheme {} // to describe properties of the theme
class theme : itheme {}// a bunch of different themes, this previously would have been the "foo"
class theme2 :itheme{} //etc.
abstract class icontroller
{
protected icontroller(itheme ptheme) {theme = ptheme;}
protected itheme theme;
//function declarations
// ....
}
class control : icontroller {} // implements the icontrol functions.
//not sure if you need more than one control implementation...
// if not, i'd get rid of the icontrol interface.
//use it by passing a theme into the controller constructor:
icontroller myUIController = new control(new ClassicTheme());
I'm trying to understand the question a little bit but if each needsAnIfoo is tied to only one type of Class and the needsAnIfoo does nothing to itself seems that you can make a static class of needsAnIfoo with extension methods no need to pass this as the constructor arg.
extension method programming guide
Here's the factory with an observer - seems to do the trick and avoids newing the "controller" inside my themed UI.
interface ifoo
{
void bar();
}
class foo : ifoo
{
public void bar() { Console.Write("do a foo type thing"); }
}
class foo2 : ifoo
{
public void bar() { Console.Write("do a foo2 type thing"); }
}
class needsAnIfoo
{
public event EventHandler SomethingIFooCanDealWith;
System.Threading.Timer _timer;
public needsAnIfoo()
{
_timer = new System.Threading.Timer(MakeFooDoSomething, null, 0, 1000);
}
void MakeFooDoSomething(Object state)
{
if (SomethingIFooCanDealWith != null)
{
SomethingIFooCanDealWith(this,EventArgs.Empty);
};
}
}
class fooFactory
{
needsAnIfoo _needsAnIfoo = new needsAnIfoo();
Dictionary<String, ifoo> _themedFoos = new Dictionary<string,ifoo>();
ifoo _lastFoo = null;
public void RegisterFoo(String themeName, ifoo foo)
{
_themedFoos.Add(themeName, foo);
}
public ifoo GetThemedFoo(String theme)
{
if (_lastFoo != null) { _needsAnIfoo.SomethingIFooCanDealWith -= (sender, e) => _lastFoo.bar(); };
ifoo newFoo = _themedFoos[theme];
_needsAnIfoo.SomethingIFooCanDealWith += (sender, e) => newFoo.bar();
_lastFoo = newFoo;
return newFoo;
}
}
static void Main(string[] args)
{
fooFactory factory = new fooFactory();
factory.RegisterFoo("CompanyA", new foo());
factory.RegisterFoo("CompanyB", new foo2());
ifoo foo = factory.GetThemedFoo("CompanyA");
Console.Write("Press key to switch theme");
Console.ReadKey();
foo = factory.GetThemedFoo("CompanyB");
Console.ReadKey();
}

Categories