How to properly use Ninject's NamedScope extension? - c#

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

Related

What is the best way to use an Interface with multiple classes where classes don't implement the same subinterfaces?

I'm trying to create an generic service-interface per logic-class to communicate with the database.
See code examples for an explanation better than words.
For example:
Foo
public interface ICreateFoo
{
void CreateFoo(Foo foo);
}
public interface IReadFoo
{
void ReadFoo(Foo foo);
}
Bar
public interface ICreateBar
{
void CreateBar(Bar bar);
}
public interface IReadBar
{
void ReadBar(Bar bar);
}
IFooService
public interface IFooService : ICreateFoo, IReadFoo, IReadBar
{ }
FooService instance
public class FooService : ICreateFoo, IReadFoo
{
public void CreateFoo(Foo foo){
//Something
}
public void ReadFoo(Foo foo){
//Something
}
}
BarService instance
public class BarService : ICreateBar, IReadBar
{
public void CreateBar(Bar bar){
//Something
}
public void ReadBar(Bar bar){
//Something
}
}
FooLogic instance
public class FooLogic : IFooService
{
private readonly IFooService _fooService;
public FooLogic(IFooService fooService) {
_fooService = fooService;
}
public void CreateFoo(Foo foo){
//Check if bar exists
if(_fooService.ReadBar())
_fooService.AddFoo(foo);
else
//nothing
}
}
But the dependency injection ofcourse doesn't know which service class instance it should get, is this a bad usage of interfaces? Because it looks clean to me, but I don't know how to implement yet.
The reason I came up with this is because I need to know if Bar exists or not before adding Foo to the database. I wanted the classes according to the SOLID-principles (each class has it's own responsibilities). Or is it better to inject each service in the Logic so, like this:
public class FooLogic
{
private readonly IFooService _fooService;
private readonly IBarService _barService;
public FooLogic(IFooService fooService, IBarService barService) {
_fooService = fooService;
_barService = barService;
}
public void CreateFoo(Foo foo){
//Check if bar exists
if(_barService.ReadBar())
_fooService.AddFoo(foo);
else
//nothing
}
}
Maybe you have a complete different but better approach, let me know! I appreciate code examples :)
Keep it simple!
Create FooService that implements IFooService.
FooLogic should be removed. You can implement the logic inside the method CreateFoo.
Since FooService will impement all the methods, you can call ReadBar() instead of _barService.ReadBar(), there is no need for composition since you already have IFooService inheriting from all other interfaces.
This way, we are still respecting the dependency injection pattern.

Autofac dynamic invocation with Func and Dependency Injection

Providing that I have a class as follows
public class Foo
{
public Foo(string someTitle, IFooService fooService)
{
// do stuff
}
}
I know that I can instantiate it like this using DI and autofac
public class Bar
{
public Bar(Func < string, IFooService, Foo > foo, IFooService fooService)
{
var foo = foo("some string", fooService);
}
}
but I'm wondering if there's any way for Bar to not have to know anything about IFooService? I'd like to not have to inject IFooService into Bar just to satisfy the func.
Essentially something like this
// pseudo code - don't use
public class Bar
{
public Bar(Func < string, Foo > foo)
{
var foo = foo("some string");
}
}
What I'm really trying to do in my app is remove all instances of Service Location, and rely solely on Dependency Injection.
Autofac should be able to do exactly what you want by using the Func<T> implicit relationship.
Here is a small repro showing how you can omit the IFooService parameter in the Func<T> and as long as the other dependencies can be resolved by Autofac, you're good to go.
Sample types that do some crazy work...
public class Bar
{
private Foo _foo;
// This constructor looks like what you're aiming for...
public Bar(Func<string, Foo> factory)
{
this._foo = factory("title");
}
public void ShowMeCoolStuff()
{
this._foo.DoWork();
}
}
public class Foo
{
private string _title;
private IFooService _service;
// The Foo class takes the title AND an IFooService...
public Foo(string title, IFooService service)
{
this._title = title;
this._service = service;
}
public void DoWork()
{
Console.WriteLine("Foo title = {0}", this._title);
this._service.DoMoreWork();
}
}
public interface IFooService
{
void DoMoreWork();
}
public class FooService : IFooService
{
public void DoMoreWork()
{
Console.WriteLine("FooService doing more work.");
}
}
When you register, make sure all the dependencies are registered - Foo, Bar, something implementing IFooService:
var builder = new ContainerBuilder();
builder.RegisterType<Foo>();
builder.RegisterType<Bar>();
builder.RegisterType<FooService>().As<IFooService>();
var container = builder.Build();
When you resolve, everything chains down the line. This resolution...
var bar = container.Resolve<Bar>();
bar.ShowMeCoolStuff();
...will yield the following console output:
Foo title = title
FooService doing more work.
There is fairly robust documentation with examples over on the Autofac site.
That's where you use factories for:
public interface IFooFactory
{
Foo CreateFoo(string value);
}
And bar can simply depend on IFooFactory.
The implementation can look as follows:
public class FooFactory : IFooFactory
{
private readonly IFooService fooService;
public FooFactory(IFooService fooService)
{
this.fooService = fooService;
}
public Foo CreateFoo(string value)
{
return new Foo(value, this.fooService);
}
}
But the given string seems like a runtime value, i.e. a value that changes from request to request or from call to call. Prevent mixing runtime values with design time dependencies as explained here, here and here. Instead, pass the runtime value as method argument to the Foo methods you are calling. That will completely remove the problem.

StructureMap - How do I use multiple objects inheriting from the same interface

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");

How can I resolve circular dependencies in Funq IoC?

I have two classes which I need to reference each other.
class Foo
{
public Foo(IBar bar) {}
}
class Bar
{
public Bar(IFoo foo) {}
}
When I do:
container.RegisterAutoWiredAs<Foo, IFoo>();
container.RegisterAutoWiredAs<Bar, IBar>();
and when I try to resolve either interface I get a circular dependency graph which results in an infinite loop. Is there an easy way to solve this in Funq or do you know of a workaround?
You can always (and in all containers, I'd say) rely on Lazy as a dependency instead, and that would yield the desired result. In Funq:
public Bar(Lazy<IFoo> foo) ...
public Foo(Lazy<IBar> bar) ...
container.Register<IBar>(c => new Bar(c.LazyResolve<IFoo>());
container.Register<IFoo>(c => new Foo(c.LazyResolve<IBar>());
The answer to your question is no, there is no easy way. Given the code above, it is impossible to construct either class without Funq, so there's no reason to expect Func to be able to do it.
var foo = new Foo(/* what do I pass here? */);
var bar = new Bar(foo);
Of course, if you had another implementation of either IFoo or IBar without the dependency, or you refactored, it might be possible.
In general, the answer to the question "how do I break up circular references when doing Dependency Injection" is: "use property injection".
class Foo
{
public Foo() {}
// Break the dependency cycle by promoting IBar to a property.
public IBar Bar { get; set; }
}
class Bar
{
public Bar(IFoo foo) {}
}
With Funq I think this would be the way to register this dependency.
container.Register<IBar>(c =>
{
var foo = new Foo();
var bar = new Bar(foo);
foo.Bar = bar;
return bar;
});
Furthermore, I agree with Tim Rogers' comment. When you have a circular dependency, there is probably a problem in your design, and you should take a look at it. This is not always wrong, but often is. However, the code you show is very abstract, and there is no way for us to give any feedback on that.
This works for me:
using Funq;
using NUnit.Framework;
namespace FunqIoCyclicReferenceTest
{
[TestFixture]
public class FunqIoCCyclicReferenceTest
{
[Test]
public void Please_Work()
{
var container = new Container();
container.Register<IBar>(c => new Bar());
container.Register<IFoo>(c => new Foo(c.Resolve<IBar>()));
var foo = container.Resolve<IFoo>();
Assert.IsNotNull(foo);
}
}
public class Foo : IFoo
{
public Foo(IBar bar)
{
bar.Foo = this;
Bar = bar;
}
public IBar Bar { get; set; }
}
public interface IBar
{
IFoo Foo { get; set; }
}
public interface IFoo
{
IBar Bar { get; set; }
}
public class Bar : IBar
{
public IFoo Foo { get; set; }
}
}
EDIT
Same idea but without side-effects in constructor:
// interfaces
public interface IBar
{
IFoo Foo { get; set; }
}
public interface IFoo
{
IBar Bar { get; set; }
}
// implementations
public class Foo : IFoo
{
public IBar Bar { get; set; }
}
public class Bar : IBar
{
public IFoo Foo { get; set; }
}
// usage
container.Register<IBar>(c => new Bar());
container.Register<IFoo>(c =>
{
var bar = c.Resolve<IBar>();
var foo = new Foo();
bar.Foo = foo;
foo.Bar = bar;
});
p.s. but I do agree with Tim Rogers - circular reference is a problem to solve.
After registering your types in the container, make the container available as a static variable:
public static class ContainerHolder
{
public static Container Container {get;set;}
}
public class Foo : IFoo
{
private IBar _bar;
public Foo(IBar bar)
{
_bar = bar;
}
}
public class Bar : IBar
{
private IFoo _foo
{
get { return ContainerHolder.Container.Resolve<IFoo>(); }
}
public Bar()
{
}
}
I had a similar scenario and the dependency between the two classes made me realize they should actually be combined into a single class.

Overloaded constructor passing the same reference multiple times

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

Categories

Resources