Lets say I have the following:
public interface IFoo
{
void Foo();
}
public interface IBar
{
void Bar();
}
public class FooAndBar : IFoo, IBar
{
//valid implementation
}
Now I have a class that takes in an IFoo and an IBar in the constructor, but has a paramter-less constructor as well.
public class Consumer
{
private IFoo foo;
private IBar bar;
public Consumer(IFoo foo, IBar bar)
{
this.foo = foo;
this.bar = bar;
}
public Consumer() : this(new FooAndBar(), new FooAndBar()) {}
}
I want to maintain the relationship between the paramter-less constructor calling the parameterized version. But I would like to pass in one referenced object rather than 'new'ing up two FooAndBar instances. Is there anyway to do this while still maintaining the relationship between the constructors?
You can create an interim private constructor that takes a FooAndBar as a parameter:
private Consumer(FooAndBar fooAndBar) : this(fooAndBar, fooAndBar) {}
public Consumer() : this(new FooAndBar()) {}
Related
I have a pattern that comes up all the time when I'm working. I am almost exclusively a web developer, and Ninject's InRequestScope handles 99% of my needs.
Here's the pattern:
// abstractions
interface IFoo {
void FooMe();
int GetSomeValue();
}
interface IBar {
void BarMe();
}
interface IFooBar {
void FooAndBar();
}
// concrete classes
class Foo : IFoo {
public void FooMe() { Console.WriteLine("I have fooed"); }
public void GetSomeValue() { return 123; }
}
class Bar : IBar {
private readonly IFoo _Foo;
public Bar(IFoo foo) { _Foo = foo; }
public void BarMe() { Console.WriteLine("Bar: {0}", _Foo.GetSomeValue()); }
}
class FooBar : IFooBar {
private readonly IFoo _Foo;
private readonly IBar _Bar;
public Bar(IFoo foo, IBar bar) { _Foo = foo; _Bar = bar; }
public void FooAndBar() {
_Foo.FooMe();
_Bar.BarMe();
}
}
// bindings
kernel.Bind<IFoo>().To<Foo>();
kernel.Bind<IBar>().To<Bar>();
kernel.Bind<IFooBar>().To<FooBar>();
What I want to do is set it up such that every time I kernel.Get<IFooBar> it creates exactly one Foo and injects it into the constructors of both Bar and FooBar.
I've experimented with this off and on using the Named Scope extension, but I've never been able to get it to work.
What is the proper binding syntax for this?
so what you've got to do is define some name:
const string FooBarScopeName = "FooBarScope";
and then define the scope:
kernel.Bind<IFooBar>().To<FooBar>()
.DefinesNamedScope(FooBarScopeName);
and bind the Foo in the named scope (the name must match!):
kernel.Bind<IFoo>().To<Foo>();
.InNamedScope(FooBarScope);
Alternative:
There's also InCallScope() which can be used if there's one kernel.Get() for each time a IFooBar is created. In that case, simply do:
kernel.Bind<IFoo>().To<Foo>().InCallScope();
When using StructureMap I would like class A to be injected with Bar and class B to be injected with Baz.
How would I configure / setup this relationship with StructureMap?
public class Bar : IFoo {}
public class Baz : IFoo {}
public class A
{
private IFoo _foo;
public A(IFoo foo)
{
_foo = foo;
}
}
public class B
{
private IFoo _foo;
public B(IFoo foo)
{
_foo = foo;
}
}
From this answer I think you need to do something like this:
For<IFoo>().Add<Bar>().Named("bar");
For<IFoo>().Add<Baz>().Named("baz");
For<A>()
.Use<A>()
.Ctor<IFoo>()
.Named("bar");
For<B>()
.Use<B>()
.Ctor<IFoo>()
.Named("baz");
I'm a .NET developer and know pretty much about OOP.
However, recently I noticed one interesting fact.
System.Data.SqlClient.SqlCommand derives from
System.Data.Common.DbCommand. The latter implements System.IDbCommand.
System.IDbCommand exposes the property Connection which an instance of IDbConnection.
In DbCommand However this property returns DbConnection type. And finally the same property in SqlCommand is of type SqlConnection
I've tried to perform the same however it gave a compile time error. How was this achieved in above example and how can I recreate the same pattern?
My code (not compiling):
public interface IFoo { }
public interface IBar
{
IFoo TheFoo();
}
public abstract class AbsFoo : IFoo { }
public abstract class AbsBar : IBar
{
public abstract AbsFoo TheFoo();
}
public class ConcreteFoo : AbsFoo { }
public class ConcreteBar : AbsBar { }
Explicit interface implementation is the name of the game here. Try this:
public abstract class AbsBar : IBar {
IFoo IFoo.TheFoo() { return this.TheFoo(); }
public abstract AbsFoo TheFoo();
}
Here's a good guide on implicit vs. explicit implementation.
I have to say that I think Richard was a little hard done by - his answer is just as good as Jason's in that they both only answered half of the question. Put them both together and you have the full answer.
To make this work with IDbCommand, DbCommand & SqlCommand there has to be an explicit implementation of IDbCommand in DbCommand (Jason's answer) and public method shadowing in SqlCommand (Richard's answer).
I'll give the full "Foo/Bar" example.
Start with these interfaces:
public interface IFoo
{
IBar GetBar();
}
public interface IBar { }
Next Foo must provide an explicit implementation of IFoo in order to return Bar, not IBar, from its own GetBar method:
public abstract class Foo : IFoo
{
IBar IFoo.GetBar()
{
return this.GetBar();
}
public Bar GetBar()
{
return this.GetBarInner();
}
protected abstract Bar GetBarInner();
}
public abstract class Bar : IBar { }
And finally a SomeFoo class must shadow GetBar to be able to return a SomeFoo instance:
public class SomeFoo : Foo
{
public new SomeBar GetBar()
{
return new SomeBar();
}
protected override Bar GetBarInner()
{
return this.GetBar();
}
}
public class SomeBar : Bar { }
I think the only information that Richard is that my adding the new keyword to the shadowed method you get rid of the compiler error.
Connection in DbCommand and SqlCommand are both just public methods. There would be a compiler warning, but it's allowed. Your code should be more like this to work like SqlCommand/DbCommand:
public interface IFoo { }
public abstract class AbsBaseBar
{
public IFoo TheFoo() { throw new NotImplementedException(); }
}
public class AbsFoo : IFoo { }
public class AbsBar : AbsBaseBar
{
public AbsFoo TheFoo() { throw new NotImplementedException(); }
}
public class ConcreteFoo : AbsFoo { }
public class ConcreteBar : AbsBar { }
I've got a class with generics which uses another class, which in return needs to know what instance of the initial class "owns" it - which causes problems ;) Let me give an example:
public interface IFoo<T>
{
}
public interface IBar
{
IFoo<IBar> Foo { get; set; }
}
public class Foo<T> : IFoo<T> where T : IBar, new()
{
private readonly T _bar;
public Foo()
{
_bar = new T {Foo = this};
}
}
class Bar : IBar
{
public IFoo<IBar> Foo { get; set; }
}
This doesn't work as Foo = this doesn't work - even if I try to cast this to IFoo (compiles but fails at run time). I've tried to tweak the code various ways, but I've not found an implementation that works...
Hopefully you see what I'm trying to do, and perhaps you even see how I can achieve this ;-)
You can solve this with a combination of an explicit cast in the constructor, along with c#4.0 support for covariance on generic parameters.
First, you need to insert a cast in the Foo<T> constructor:
_bar = new T {Foo = (IFoo<IBar>)this};
Just doing that isn't sufficient, though. Your constraint that T : new() means that T needs to be a concrete class. As such, IFoo<T> will never be exactly IFoo<IBar>. However, if you specify that the generic parameter T for IBar<T> is covariant, then the cast from IFoo<Bar> to IFoo<IBar> will become legal:
public interface IFoo<out T>
The out keyword specifies that the parameter is covariant (which essentially means "this parameter will only be output by methods, never input.")
This MSDN article offers more details on covariance and contravariance.
Would declaring the T type parameter of IFoo as covariant solve your problem?
This code should allow you to do what you are trying:
public interface IFoo<out T> {
}
public interface IBar {
IFoo<IBar> Foo { get; set; }
}
public class Foo<T> : IFoo<T> where T : IBar, new() {
private readonly T _bar;
public Foo() {
_bar = new T { Foo = (IFoo<IBar>)this };
}
}
class Bar : IBar {
public IFoo<IBar> Foo { get; set; }
}
public static class Program {
public static void Main(params string[] args) {
Bar b = new Bar();
Foo<Bar> f = new Foo<Bar>();
}
}
I have a situation where i have a class
class Foo
{
Foo Bar()
{
return new Foo();
}
}
Now i wan tot create an interface for it
class IFoo
{
??? Bar();
}
What should be in place of the question marks? Each class should return it's own type, not Foo.
The solutions below work but do not looks clean. I don't understand why i have to specify the same class twice, and there is nothing like "this" for the current type
This is how i am using it later
class GenericClass<T> where T : IFoo
{
T foo = new T();
T item = foo.Bar();
}
You ask:
The solutions below work but do not looks clean. I don't understand why i have to specify the same class twice, and there is nothing like "this" for the current type
The reason why you have to specify it twice is because C# lacks the feature that you need.
What you want is something like this:
interface IFoo
{
IFoo Bar();
}
class Foo : IFoo
{
Foo Bar() // should work since Foo is an IFoo, but it's not supported by C#
{
return new Foo();
}
}
From a type-safety point of view, this should work (it's called return type covariance). In fact, other programming languages such as C++ or Java support this, see this example on Wikipedia. Unfortunately, return type covariance is not supported by C# (not even C# 4.0, which introduced covariance for generics), which is why you have to use the "generics workaround" illustrated in the other answers.
Covariant return types as well as a "this" type are proposed features for new versions of C#:
Champion "Covariant Return Types"
Proposal: support "type of the current object" as declared return type.
You could add a generic type and constrain it using the interface type:
public interface IFoo<T>
{
T Bar();
}
You'd implement this as follows:
public class Foo : IFoo<Foo>
{
public Foo Bar()
{
return new Foo();
}
}
public class Cheese : IFoo<Cheese>
{
public Cheese Bar()
{
return new Cheese();
}
}
Update, if you never care about the concrete return type of Foo, then you can do the following:
public interface IFoo
{
IFoo Bar();
}
Which is implemented like:
public class Foo : IFoo
{
public IFoo Bar()
{
return new Foo();
}
}
Then in your generic class:
public class GenericClass<T> where T : class, IFoo, new()
{
public T Rar()
{
T foo = new T();
T item = foo.Bar() as T;
return item;
}
}
GenericClass<Foo>.Rar(); will be a concrete implementation of Foo.
I think that the real question is: why you need the derived type in the interface? Interface is exactly for that reason - abstracting from the concrete classes. If it's just for convenience, so you don't have to cast to Foo after calling Bar(), you can implement the interface explicitly:
interface IFoo
{
IFoo Bar();
}
class Foo : IFoo
{
public Foo Bar()
{
return new Foo();
}
IFoo IFoo.Bar()
{
return Bar();
}
}
Ask yourself the question: why do you introduce an interface when you want the concrete type?
You can use an abstract base class plus explicit member implementation to achieve this. First, declare your interface like this:
interface IFoo
{
IFoo Bar();
}
Then, declare a generic abstract class that implements IFoo in an explicit manner, and also declares an abstract method that kind of "overloads" Bar(), but in a generic manner:
abstract class BaseFooImpl<T> : IFoo where T : BaseFooImpl
{
public abstract T Bar();
IFoo IFoo.Bar()
{
return Bar(); // this will call the abstract Bar()
}
}
Now, define your concrete classes like this:
class ConcreteFoo : BaseFooImpl<ConcreteFoo>
{
public override ConcreteFoo Bar()
{
return this; // for example, of course.
}
}
The advantage of this approach is that you can always use non-generic IFoo references to hold concrete instances. If you make your interface generic, you can't, for instance, declare these:
IFoo mammalInstance, fishInstance; // Instead of IFoo<Mammal> mammalInstance; IFoo<Fish> fishInstance;
List<IFoo> manyInstances; // Instead of List<IFoo<IFoo>>, which doesn't even work AFAIK
public interface IFoo<T>
{
T Bar();
}
Your implementation would then be:
class Foo : IFoo<Foo>
{
Foo Bar()
{
return new Foo();
}
}
class Baz : IFoo<Baz>
{
Baz Bar()
{
return new Baz();
}
}
You need to make the interface generic, like this:
interface IFoo<TClass> where TClass : IFoo<TClass>, class {
TClass Bar();
}
Not sure what you are trying to accomplish but it could be done this way:
interface IFoo<T>
{
T Bar();
}
class Foo:IFoo<Foo>
{
#region IFoo<Foo> Members
public Foo Bar()
{
return new Foo();
}
#endregion
}
Or Like this:
interface IFoo
{
IFoo Bar();
}
class Foo : IFoo
{
#region IFoo Members
public IFoo Bar()
{
return new Foo();
}
#endregion
}