autofac "Hello World" app in C# - initialization - dependency-injection

I am looking for some help with a simple "Hello World" example of DI. What I don't understand is how to initialize the classes "Foo" and "Bar" within a DI framework (autofac).
namespace AutofacTesting
{
//these classes are intended to be used with autofac / DI
public interface IFooBar
{
void Draw();
}
public class Bar : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing something in Bar");
}
}
public class Foo : IFooBar
{
public void Draw()
{
MessageBox.Show("Drawing somthing in Foo");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().As<IFooBar>();
builder.RegisterType<Foo>().As<IFooBar>();
var container = builder.Build();
var taskController = container.Resolve<IFooBar>();
taskController.Draw();
int a = 1;
}
}
}

I think you mean you want to resolve a Bar or Foo class as the concrete implementation, not instantiate it. If so you could write:
var builder = new ContainerBuilder();
builder.RegisterType<Bar>().Named<IFooBar>("Bar");
builder.RegisterType<Foo>().Named<IFooBar>("Foo");
var container = builder.Build();
var taskController = container.ResolveNamed<IFooBar>("Bar");
taskController.Draw();
I also realize this is a hello world application, but be careful not to fail into the anti-pattern of using a service locator (i.e. using contain.Resolve all over the place). Instead, consider designs which will allow you to have all the registration and resolving happen in the same place, named a composition root.
I mention this caution becuase having this level of ambiguity (i.e. multiple concreate types being registered for a given interface) can cause one to start using the service locator pattern. Instead, in more complex applications, consider refactoring your API to have less ambiguity upon resolving registered types.

Related

android MVP & DI

I am creating an android app and I write following classes and interface and codes .Because I try to use MVP pattern , But now I am not sure that my codes are standard or not ?
should I use Dagger2 for Di or should not?
model , presenter class are below:
public class ChangePasswordModel{
public void saveChange(final String oldPass, final String newPass, final ChangePasswordCallback callback) {
/*in real world it change password with API*/
callback.onDo();
} }
my presenter is :
public class ChangePasswordPresenter{
private ChangePasswordContract.View mView;//this is an interface to interact with Activity
public ChangePasswordPresenter(ChangePasswordContract.View mView) {
this.mView = mView;
}
public void pSaveChange(String oldPass, String newPass) {
ChangePasswordModel model = new ChangePasswordModel();
model.saveChange(oldPass, newPass, new ChangePasswordCallback() {
#Override
public void onDo() {
mView.showMessage("password Changed");
}
});
}
}
Do I implemented MVP correctly?
Should I use Dagger2 for DI? why?
The sample codes that you mentioned in your question is a correct implementation of MVP which can get improved by some changes.
The best practice is a mixture of Dagger, MVP, RxJava, Retrofit and Mock tests which improve the quality and readability of your project. MVP helps you with a clean and separate layered code and RxJava will help with wiring different layers up together and Dagger2 can really helps you with managing dependencies and also make your Mocking in test easy.
You can take a look at this sample project repo on my Github which has been developed using Dagger, MVP and there are also some test available:
http://github.com/mmirhoseini/fyber_mobile_offers
It needs to be improved in my opinion. You Model class must be a concrete object class however your ChangePasswordModel contains saveChange() method that have no idea why it's calling a callback. This logic must be implemented in Presenter class.
Basically process of following MVP design pattern is as follows:
create a package based on your screen. Let's say you have a Signup screen. Then create a package, <your.main.package>.signupscreen.
Create three classes of SignupActivity, SignupView(this is interface), SignupPresenter.
SignupView interface:
interface SignUpView {
String getFirstName();
String getLastName();
String getEmailAddress();
String getPassword();
}
SignupActivity implements SignUpView and holds a reference of SignupPresenter.
public class SignUpActivity implements SignUpView {
#Inject
public Service mService;
SignUpPresenter mSignUpPresenter;
#Override
protected void onStart() {
super.onStart();
mSignUpPresenter = new SignUpPresenter(mService, this);
}
#Override
protected void onStop() {
super.onStop();
if (mSignUpPresenter != null) {
mSignUpPresenter.onStop();
}
}
#Override
public String getFirstName() {
return etFirstName.getText().toString().trim();
}
#Override
public String getLastName() {
return etLastName.getText().toString().trim();
}
#Override
public String getEmailAddress() {
return etEmail.getText().toString().trim();
}
#Override
public String getPassword() {
return etPassword.getText().toString().trim();
}
}
And finally SignupPresenter class:
class SignUpPresenter implements SignUpCallback {
private final Service service;
private final SignUpView view;
private CompositeSubscription subscriptions;
SignUpPresenter(Service service, SignUpView view) {
this.service = service;
this.view = view;
this.subscriptions = new CompositeSubscription();
}
void onStop() {
subscriptions.unsubscribe();
}
}
This is very basic implementation of Activity based on MVP. I do recommend to have a look at this awesome doc regard MVP, Retrofit and Dagger 2, A Simple Android Apps with MVP, Dagger, RxJava, and Retrofit

Autofac get decorated QueryHandler by convention based on constructor parameter name?

We inject IQueryHandler<TQUery,TResult> into our MVC controllers. We globally register all of these in the container
We have written a decorator that can cache the results of IQueryHandler.
We want to sometimes get cached reults and other times not from the same handler.
Is it possible to conditionally get a decorated handler based on the name of the constructor parameter. e.g. inject IQueryHandler<UnemployedQuery, IEnumerable<People>> cachedPeopleHandler if we prefix constructor parameter name with cached we actually get it wrapped with decorator?
Just trying to use a more convention over configuration approach to simplify things.
Yes it's possible to do it. Below is a simple working example on how you can achieve it:
class Program
{
public interface IQueryHandler{}
private class QueryHandler : IQueryHandler
{
}
private class CacheQueryHandler : IQueryHandler
{
}
public interface IService
{
}
private class Service : IService
{
private readonly IQueryHandler _queryHandler;
private readonly IQueryHandler _cacheQueryHandler;
public Service(IQueryHandler queryHandler, IQueryHandler cacheQueryHandler)
{
_queryHandler = queryHandler;
_cacheQueryHandler = cacheQueryHandler;
}
public override string ToString()
{
return string.Format("_queryHandler is {0}; _cacheQueryHandler is {1}", _queryHandler,
_cacheQueryHandler);
}
}
static void Main(string[] args)
{
var builder = new ContainerBuilder();
// Register the dependency
builder.RegisterType<QueryHandler>().As<IQueryHandler>();
// Register the decorator of the dependency
builder.RegisterType<CacheQueryHandler>().Keyed<IQueryHandler>("cache");
// Register the service implementation
builder.RegisterType<Service>().AsSelf();
// Register the interface of the service
builder.Register(c =>
{
var ctor = typeof (Service).GetConstructors()[0];
var parameters =
ctor.GetParameters()
.Where(p => p.Name.StartsWith("cache"))
.Select(p => new NamedParameter(p.Name, c.ResolveKeyed("cache", p.ParameterType)));
return c.Resolve<Service>(parameters);
}).As<IService>();
using (var container = builder.Build())
{
var service = container.Resolve<IService>();
Console.WriteLine(service.ToString());
Console.ReadKey();
}
}
}
Update:
Basically you need to:
1. Think up a general convention. Prefix "cache" of ctor parameter name in your case.
2. Register your dependencies as usual.
3. Register your decorators, so they don't overwrite your original dependencies and you can easily resolve them basing on your convention. e.g. Keyed, Named, via Attribute, etc.
4. Register you actual implementation of class that uses decorators
5. Register your interface that describes the class via lambda expression that has all magic inside.
Note: I provided just a simple and working example. It's on you to make it nice, easy to use and fast e.g. make it as an extension, generic, cache reflection results etc. It's not difficult anyway.
Thanks.

SimpleInjector - Register a type for all it's interfaces

Is it possible to register a type for all it's implementing interfaces? E.g, I have a:
public class Bow : IWeapon
{
#region IWeapon Members
public string Attack()
{
return "Shooted with a bow";
}
#endregion
}
public class HumanFighter
{
private readonly IWeapon weapon = null;
public HumanFighter(IWeapon weapon)
{
this.weapon = weapon;
}
public string Fight()
{
return this.weapon.Attack();
}
}
[Test]
public void Test2b()
{
Container container = new Container();
container.RegisterSingle<Bow>();
container.RegisterSingle<HumanFighter>();
// this would match the IWeapon to the Bow, as it
// is implemented by Bow
var humanFighter1 = container.GetInstance<HumanFighter>();
string s = humanFighter1.Fight();
}
It completely depends on your needs, but typically you need to use the Container's non-generic registration method. You can define your own LINQ queries to query the application's metadata to get the proper types, and register them using the non-generic registration methods. Here's an example:
var weaponsAssembly = typeof(Bow).Assembly;
var registrations =
from type in weaponsAssembly.GetExportedTypes()
where type.Namespace.Contains(".Weapons")
from service in type.GetInterfaces()
select new { Service = service, Implementation = type };
foreach (var reg in registrations)
{
container.Register(reg.Service, reg.Implementation);
}
If you need to batch-register a set of implementations, based on a shared generic interface, you can use the RegisterManyForOpenGeneric extension method:
// include the SimpleInjector.Extensions namespace.
container.RegisterManyForOpenGeneric(typeof(IValidator<>),
typeof(IValidator<>).Assembly);
This will look for all (non-generic) public types in the supplied assembly that implement IValidator<T> and registers each of them by their closed-generic implementation. If an type implements multiple closed-generic versions of IValidator<T>, all versions will be registered. Take a look at the following example:
interface IValidator<T> { }
class MultiVal1 : IValidator<Customer>, IValidator<Order> { }
class MultiVal2 : IValidator<User>, IValidator<Employee> { }
container.RegisterManyForOpenGeneric(typeof(IValidator<>),
typeof(IValidator<>).Assembly);
Assuming the given interface and class definitions, the shown RegisterManyForOpenGeneric registration is equivalent to the following manual registration:
container.Register<IValidator<Customer>, MultiVal1>();
container.Register<IValidator<Order>, MultiVal1>();
container.Register<IValidator<User>, MultiVal2>();
container.Register<IValidator<Employee>, MultiVal2>();
It would also be easy to add convenient extension methods. Take for instance the following extension method that allows you to register a single implementation by all its implemented interfaces:
public static void RegisterAsImplementedInterfaces<TImpl>(
this Container container)
{
foreach (var service in typeof(TImpl).GetInterfaces())
{
container.Register(service, typeof(TImpl));
}
}
It can be used as follows:
container.RegisterAsImplementedInterfaces<Sword>();

How do I handle classes with static methods with Ninject?

How do I handle classes with static methods with Ninject?
That is, in C# one can not have static methods in an interface, and Ninject works on the basis of using interfaces?
My use case is a class that I would like it to have a static method to create an
unpopulated instance of itself.
EDIT 1
Just to add an example in the TopologyImp class, in the GetRootNodes() method, how would I create some iNode classes to return? Would I construct these with normal code practice or would I somehow use Ninject? But if I use the container to create then haven't I given this library knowledge of the IOC then?
public interface ITopology
{
List<INode> GetRootNodes();
}
public class TopologyImp : ITopology
{
public List<INode> GetRootNodes()
{
List<INode> result = new List<INode>();
// Need code here to create some instances, but how to without knowledge of the container?
// e.g. want to create a few INode instances and add them to the list and then return the list
}
}
public interface INode
{
// Parameters
long Id { get; set; }
string Name { get; set; }
}
class NodeImp : INode
{
public long Id
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public string Name
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
// Just background to highlight the fact I'm using Ninject fine to inject ITopology
public partial class Form1 : Form
{
private ITopology _top;
public Form1()
{
IKernel kernal = new StandardKernel(new TopologyModule());
_top = kernal.Get<ITopology>();
InitializeComponent();
}
}
If you're building a singleton or something of that nature and trying to inject dependencies, typically you instead write your code as a normal class, without trying to put in lots of (probably incorrect) code managing the singleton and instead register the object InSingletonScope (v2 - you didnt mention your Ninject version). Each time you do that, you have one less class that doesnt surface its dependencies.
If you're feeling especially bloody-minded and are certain that you want to go against that general flow, the main tools Ninject gives you is Kernel.Inject, which one can use after you (or someone else) has newd up an instance to inject the dependencies. But then to locate one's Kernelm you're typically going to be using a Service Locator, which is likely to cause as much of a mess as it is likely to solve.
EDIT: Thanks for following up - I see what you're after. Here's a hacky way to approximate the autofac automatic factory mechanism :-
/// <summary>
/// Ugly example of a not-very-automatic factory in Ninject
/// </summary>
class AutomaticFactoriesInNinject
{
class Node
{
}
class NodeFactory
{
public NodeFactory( Func<Node> createNode )
{
_createNode = createNode;
}
Func<Node> _createNode;
public Node GenerateTree()
{
return _createNode();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToMethod( context => () => Kernel.Get<Node>() );
}
}
[Fact]
public void CanGenerate()
{
var kernel = new StandardKernel( new Module() );
var result = kernel.Get<NodeFactory>().GenerateTree();
Assert.IsType<Node>( result );
}
}
The ToMethod stuff is a specific application of the ToProvider pattern -- here's how you'd do the same thing via that route:-
...
class NodeProvider : IProvider
{
public Type Type
{
get { return typeof(Node); }
}
public object Create( IContext context )
{
return context.Kernel.Get<Node>();
}
}
internal class Module : NinjectModule
{
public override void Load()
{
Bind<Func<Node>>().ToProvider<NodeProvider>();
}
}
...
I have not thought this through though and am not recommending this as A Good Idea - there may be far better ways of structuring something like this. #Mark Seemann? :P
I believe Unity and MEF also support things in this direction (keywords: automatic factory, Func)
EDIT 2: Shorter syntax if you're willing to use container-specific attributes and drop to property injection (even if Ninject allows you to override the specific attributes, I much prefer constructor injection):
class NodeFactory
{
[Inject]
public Func<Node> NodeFactory { private get; set; }
public Node GenerateTree()
{
return NodeFactory();
}
}
EDIT 3: You also need to be aware of this Ninject Module by #Remo Gloor which is slated to be in the 2.4 release
EDIT 4: Also overlapping, but not directly relevant is the fact that in Ninject, you can request an IKernel in your ctor/properties and have that injected (but that doesn't work directly in a static method).

interface<T> binding in Castle Windsor

I have a common datacontainer
interface IDataContainer
I use it for different types of T
IPerson, ISuperMan etc
In castle i regsiter it with
container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);
at runtime castle creates the dependency with eg.
IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();
but it fails with an unable to cast...the classes implements the interface and namespaces are correct etc.
The call
IPerson test = container.GetService<IPerson>();
Works (with the registration of <IPerson,Person>)
Cant castle resolve an interface<T> or ?
So this is way late, but I think I know what you're trying to do here. I'm able to get this to pass:
IDataContainer<IPerson> test = container.GetService<IDataContainer<IPerson>>();
By registering components like this:
public class IoC
{
public static void SetUp()
{
container = new WindsorContainer();
container.AddComponent<IPerson, Person>();
//container.AddComponentWithLifestyle<IDataContainer<IPerson>, DataContainer<Person>>(LifestyleType.Transient);
//container.AddComponentWithLifestyle<IDataContainer<ISuperMan>, DataContainer<SuperMan>>(LifestyleType.Transient);
container.AddComponentWithLifestyle("DataContainers", typeof(IDataContainer<>), typeof(DataContainer<>), LifestyleType.Transient);
}
public void TestOne()
{
SetUp();
var test = container.GetService<IDataContainer<IPerson>>();
Assert.That(test, Is.Not.Null);
}
public void TestTwo()
{
SetUp();
var test = container.GetService<IPerson>();
Assert.That(test, Is.Not.Null);
}
}
internal interface IDataContainer<T> { }
internal class DataContainer<T> : IDataContainer<T> { }
internal interface IPerson { }
class Person : IPerson { }
internal interface ISuperMan { }
class SuperMan : ISuperMan { }
The two lines that are commented out are the two lines that exist in the question.
This has nothing to do with Windsor. You get a casting error because C# 2.0 and 3.0 do not support generics covariance. You're probably making DataContainer<T> implement IDataContainer<T>, which means that DataContainer<Person> implements IDataContainer<Person> and not IDataContainer<IPerson> which is what you're requesting from the container.

Resources