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

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();
}

Related

Declaring resolution to ambiguous constructor reference

Consider the following class
class Foo
{
public Foo(IBar bar=null)
{
}
}
I have a need to inject an alternate constructor to allow the IBar instance to be provided on demand rather than injected.
class Foo
{
public Foo(IBar bar=null)
{
}
public Foo(Func<IBar> barFunc) : this((IBar)null)
{
}
}
However there is a bunch of code in several dependent projects like:
Foo foo = new Foo(null);
This code won't compile anymore due to the ambiguous constructor reference.
Obviously I could change the code to
Foo foo = new Foo((IBar)null);
But this would require changes to a whole bunch of projects, and my goal is a transparent change. Is there some way to specify which constructor to call if ambiguous? Or a way to indicate to the compiler that barFunc cannot be null
At the moment, I am looking at this but it feels .... dirty
class Foo
{
public Foo(IBar bar=null)
{
}
public Foo(Func<IBar> barFunc, bool notUsed) : this((IBar)null)
{
}
}
Maybe use a static method ala named constructor idiom:
class Foo
{
...
public static Foo Create(Func<IBar> func)
{
return new Foo(func());
}
}
Make the Foo(Func<IBar>) constructor private, and add a factory method:
public static Foo WithIBarFunc(Func<IBar> func) {
return new Foo(func);
}
If you can, delete the the Foo(Func<IBar>) constructor all together and write the method like this:
public static Foo WithIBarFunc(Func<IBar> func) {
var foo = new Foo(null);
// initialise foo with func...
return foo;
}

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.

Inject a singleton with parameters

Using Ninject, I have an interface that I want to bind to single instance of a concrete implementation. For example:
public interface IFoo { //... }
public class Foo { //... }
Now normally, I'd just bind something like this like so:
kernel.Bind<IFoo>().To<Foo>().InSingletonScope();
But, I need to add parameters to the constructor for Foo. Normally, again, that wouldn't be too much of a problem (I think):
kernel.Bind<IFoo>()
.To<Foo>()
.InSingletonScope()
.WithConstructorArgument("bar", myBar);
Now the problem is that I can't know the value of myBar at the time I set up all my bindings. I need to defer that until the first time I need an IFoo (and note, in reality I have several arguments to pass). So what I need is a singleton, that will be lazy initialized on first use and only gets arguments at that point.
What's the best way to approach this? I'm assuming something with Factory is probably the solution, but I don't quite see the right way to do this. I don't want to create a new Foo every time.
As in my comment above. the real problem is that you may not have the construction parameters when you need Foo. In this pattern you can Bind all your interfaces as you please and call IInitialiser.Initialise when you are ready (obvs you need to keep a reference or make it static).
Foo will throw an exception if you call it before its been properly set up
IFoo remains unchanged
IInitialiser implementations can be tweaked to poll a DB or respond to events or whatever suits your late configuration senario best
using System;
namespace UnitTestProject3
{
public interface IFoo
{
int GetAllTheFoo();
}
public interface IInitialiser
{
void Initialise(int x);
int GetX();
bool IsReady { get; }
}
public class Foo : IFoo
{
private bool isInitalised;
private int x;
private IInitialiser i;
public Foo(IInitialiser i)
{
this.isInitalised = false;
this.i = i;
}
protected void Init()
{
if (this.isInitalised)
{
return;
}
else if (i.IsReady)
{
x = i.GetX();
this.isInitalised = true;
return;
}
else
{
throw new Exception("you have not set x");
}
}
public int GetAllTheFoo()
{
Init();
return x;
}
}
}
You can use the Factory extension.
public interface IFooFactory
{
IFoo CreateFoo(string bar);
IFoo CreateFoo();
}
public interface IFoo
{
string Bar { get; set; }
}
public class Foo : IFoo
{
public string Bar { get; set; }
public Foo(string bar)
{
Bar = bar;
}
}
kernel.Bind<IFoo>().To<Foo>().InSingletonScope();
kernel.Bind<IFooFactory>().ToFactory();
IFoo foo1 = fooFactory.CreateFoo("myBar");
IFoo foo2 = fooFactory.CreateFoo("myDifferentBar"); // value is basically ignored here
IFoo foo3 = fooFactory.CreateFoo();
This will always return the same instance of Foo. Of course if you call the paremeterless method first it will result in an exception.
Given the other two answers, I could be completely missing the point of the question, but why would not something as simple as this work for you:
kernel.Bind<IFoo>().ToMethod(x => CreateFoo()).InSingletonScope();
CreateFoo will be responsible for constructing your single object with whatever set of parameters that you need. By the time CreateFoo is called you should already know what the parameters are.

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

Ninject. Optional Injection

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();
}
}

Categories