Autofac: registering hierarchy of classes - autofac

I am struggling to register with Autofac a hierarchy of classes and interfaces.
I have an interface IMyService defined as below:
public interface IMyService
{
void DoMyService();
}
And I have two abstract classes with implement this interface and called MyServiceA, and MyServiceB:
public abstract class MyServiceA : IMyService
{
public abstract DoMyService();
}
public abstract class MyServiceB : IMyService
{
public abstract DoMyService();
}
Moreover I have a second-level hierarchy for each of the two aforementioned services: MyServiceA1, MyServiceA2, MyServiceB1 and MyServiceB2:
public class MyServiceA1 : MyServiceA
{
public MyServiceA1() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceA2 : MyServiceA
{
public MyServiceA2() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceB1 : MyServiceB
{
public MyServiceB1() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
public class MyServiceB2 : MyServiceB
{
public MyServiceB2() : base() {}
public void DoMyService()
{
// Implementation goes here
}
}
I have in input two enums FirstEnum and SecondEnum used to select which of the four concrete types to instantiate:
public enum FirstEnum
{
SvcA,
SvcB
}
public enum SecondEnum
{
Svc1,
Svc2
}
I want to register IMyService and by providing two enums, It will automatically instantiate the good concrete type.
For instance, if I want to resolve an IMyService and I provide FirstEnum.SvcB and SecondEnum.Svc2, it should instantiate the concrete type MyServiceB2 class. Moreover this hierarchy might be updated by adding some other concrete types etc, so I need a generic way of doing it
Does anyone have a clue to help me?
Thanks

If you want to create a specific service dynamically depending on a set of parameters, this is a good use case for an abstract factory:
public interface IMyServiceFactory
{
IMyService Create(FirstEnum e1, SecondEnum e2);
}
public class MyServiceFactory : IMyServiceFactory
{
private readonly ILifetimeScope scope;
public MyServiceFactory(ILifetimeScope scope)
{
if (scope == null)
throw new ArgumentNullException("scope");
this.scope = scope;
}
public IMyService Create(FirstEnum e1, SecondEnum e2)
{
if (e1 == FirstEnum.SvcA)
{
if (e2 == SecondEnum.Svc1)
{
return scope.Resolve<MyServiceA1>();
}
else //svc2
{
return scope.Resolve<MyServiceA2>();
}
}
else //B
{
if (e2 == SecondEnum.Svc1)
{
return scope.Resolve<MyServiceB1>();
}
else //svc2
{
return scope.Resolve<MyServiceB2>();
}
}
}
}
And now your consumer need to get the factory injected instead of the service:
public class MyServiceConsumer
{
private readonly IMyServiceFactory factory;
public MyServiceConsumer(IMyServiceFactory factory)
{
this.factory = factory;
}
public void Do()
{
//var service = this.factory.Create
}
}
Registration :
Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
builder.RegisterType<MyServiceA1>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceA2>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceB1>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceB2>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<MyServiceFactory>().As<IMyServiceFactory>();
builder.RegisterType<MyServiceConsumer>();
//and quick test resolve
var container = builder.Build();
var test = container.Resolve<MyServiceConsumer>();

Related

Why am I getting "OneTimeSetUp: No suitable constructor was found..."?

I am using NUnit3 and trying to make use of TestFixtureSource in the following class hierarchy:
public class AtataTestFixtureData
{
public static IEnumerable FixtureParams
{
get
{
yield return new TestFixtureData(new AtataConfigContainer
{
AtataJsonConfig = new BaseAtataConfig()
});
}
}
}
[TestFixtureSource(typeof(AtataConfigContainer), nameof(AtataTestFixtureData.FixtureParams))]
public class AtataTestsWithDbBase : OzCsTestsWithDbBase, IAtataAbpTests
{
public AtataTestsWithDbBase()
{
}
public AtataTestsWithDbBase(AtataConfigContainer aAtataConfigContainer)
{
AtataAbpTestsAdapter = AtataAbpTestsAdapter.Instance;
AtataConfigContainer = aAtataConfigContainer;
}
}
public class SomeSiteComAuTestsBase : AtataTestsWithDbBase
{
public SomeSiteComAuTestsBase(AtataConfigContainer aAtataConfigContainer) : base(aAtataConfigContainer)
{
}
}
[TestFixture]
public class IndexTests : SomeSiteComAuTestsBase
{
/// <summary>
/// Class constructor.
/// </summary>
public IndexTests(AtataConfigContainer aAtataConfigContainer) : base(aAtataConfigContainer)
{
}
[Test]
public void Get()
{
//Arrange
//Act
IndexPageObject indexPage = Go.To<IndexPageObject>();
//Assert
}
}
When I run IndexTests.Get() I get the exception OneTimeSetUp: No suitable constructor was found but according to public IndexTests(AtataConfigContainer aAtataConfigContainer) : base(aAtataConfigContainer) I have the needed constructor.
What am I missing here?
You are getting this error because your IndexTests class has a constructor that takes parameters, but your TestFixtureSource is on a base class. The TestFixtureSource needs to be on your IndexTests. The TestFixtureSource attribute is not inherited.

Injecting a Factory that accepts a Parameter with AutoFac

I've read over several examples that were more complex then I needed and I'm having trouble distilling this down to a simple, concise pattern.
Let's say I have an interface names ICustomService and multiple implementations of ICustomService. I also have a class Consumer that needs to determine at run time which ICustomService to use based upon a parameter.
So I create a classes as follows:
public class Consumer
{
private CustomServiceFactory customServiceFactory;
public Consumer(CustomServiceFactory _customServiceFactory)
{
customServiceFactory = _customServiceFactory;
}
public void Execute(string parameter)
{
ICustomService Service = customServiceFactory.GetService(parameter);
Service.DoSomething();
}
}
public class CustomServiceFactory
{
private IComponentContext context;
public CustomServiceFactory(IComponentContext _context)
{
context = _context;
}
public ICustomService GetService(string p)
{
return context.Resolve<ICustomService>(p); // not correct
}
}
public class ServiceA : ICustomService
{
public void DoSomething()
{
}
}
public class ServiceB : ICustomService
{
public void DoSomething()
{
}
}
Is there an advantage to having my factory implement an interface? How do I fix my factory and register these classes with Autofac so that Consumer.Execute("A") calls DoSomething on WorkerA and Consumer.Execute("B") calls DoSomething on WorkerB?
Thank you
You would register your implementations of ICustomService with keys. For example:
builder.RegisterType<FooService>.Keyed<ICustomService>("someKey");
builder.RegisterType<BarService>.Keyed<ICustomService>("anotherKey");
and then your factory method would be:
public ICustomService GetService(string p)
{
return context.ResolveKeyed<ICustomService>(p);
}
But, you can take this a step further and decouple CustomServiceFactory from IComponentContext:
public class CustomServiceFactory
{
private Func<string, ICustomService> _create;
public CustomServiceFactory(Func<string, ICustomService> create)
{
_create = create;
}
public ICustomService GetService(string p)
{
return _create(p);
}
}
which you would register like so:
builder.Register(c => {
var ctx = c.Resolve<IComponentContext>();
return new CustomServiceFactory(key => ctx.ResolveKeyed<ICustomService>(key));
});
And at that point, assuming CustomServiceFactory doesn't have any other behavior that was omitted for the question, then you as might as well just use and register Func<string, ICustomService> directly.

MvvmCross: IoC with Decorator pattern, two implementations of the same interface

I'd like to implement the Decorator pattern in one of my Mvx projects. That is, I'd like to have two implementations of the same interface: one implementation that is available to all of the calling code, and another implementation that is injected into the first implementation.
public interface IExample
{
void DoStuff();
}
public class DecoratorImplementation : IExample
{
private IExample _innerExample;
public Implementation1(IExample innerExample)
{
_innerExample = innerExample;
}
public void DoStuff()
{
// Do other stuff...
_innerExample.DoStuff();
}
}
public class RegularImplementation : IExample
{
public void DoStuff()
{
// Do some stuff...
}
}
Is it possible to wire up the MvvmCross IoC container to register IExample with a DecoratorImplementation containing a RegularImplementation?
It depends.
If DecoratorImplementation is a Singleton, then you could do something like:
Mvx.RegisterSingleton<IExample>(new DecoratorImplementation(new RegularImplementation()));
Then calls to Mvx.Resolve<IExample>() will return the instance of DecoratorImplementation.
However, if you need a new instance, unfortunately the MvvmCross IoC Container doesn't support that. It would be nice if you could do something like:
Mvx.RegisterType<IExample>(() => new DecoratorImplementation(new RegularImplementation()));
Where you'd pass in a lambda expression to create a new instance, similar to StructureMap's ConstructedBy.
Anyway, you may need to create a Factory class to return an instance.
public interface IExampleFactory
{
IExample CreateExample();
}
public class ExampleFactory : IExampleFactory
{
public IExample CreateExample()
{
return new DecoratorImplementation(new RegularImplementation());
}
}
Mvx.RegisterSingleton<IExampleFactory>(new ExampleFactory());
public class SomeClass
{
private IExample _example;
public SomeClass(IExampleFactory factory)
{
_example = factory.CreateExample();
}
}

Using Ninject custom instance providers to bind successfully using factory method argument to resolve

I've been studying this accepted answer to a similar question in which what I believe is a concrete factory returns an implementation based on a string argument on the factory method matching a named binding on the concrete implementation.
I'm struggling to get a slightly more complex example to work properly when the factory is an abstract factory, and I wish to use Ninject convention-based binding. Consider the following test:
[Fact]
public void VehicleBuilderFactory_Creates_Correct_Builder_For_Specified_Client()
{
// arrange
StandardKernel kernel = new StandardKernel();
kernel.Bind(typeof (IVehicleBuilderFactory<,>))
.ToFactory(() => new UseFirstArgumentAsNameInstanceProvider())
.InSingletonScope();
kernel.Bind(scanner => scanner
.FromThisAssembly()
.SelectAllClasses()
.WhichAreNotGeneric()
.InheritedFrom(typeof(IVehicleBuilder<>))
.BindAllInterfaces());
var bicycleBuilderFactory =
kernel.Get<IVehicleBuilderFactory<IVehicleBuilder<BlueBicycle>, BlueBicycle>>();
string country = "Germany";
string localizedColor = "blau";
// act
var builder = bicycleBuilderFactory.Create<IVehicleBuilder<BlueBicycle>>(country);
Bicycle Bicycle = builder.Build(localizedColor);
// assert
Assert.IsType<BlueBicycleBuilder_Germany>(builder);
Assert.IsType<BlueBicycle>(Bicycle);
Assert.Equal(localizedColor, Bicycle.Color);
}
Here's where I try juggling with torches & knives 'cause I saw it on the internet once:
public class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider
{
protected override string GetName(MethodInfo methodInfo, object[] arguments) {
return methodInfo.GetGenericArguments()[0].Name + "Builder_" + (string)arguments[0];
// ex: Germany -> 'BlueBicycle' + 'Builder_' + 'Germany' = 'BlueBicyleBuilder_Germany'
}
protected override ConstructorArgument[] GetConstructorArguments(MethodInfo methodInfo, object[] arguments) {
return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
}
}
I get stabbed and set ablaze when I try to assign bicycleBuilderFactory with this error:
System.InvalidCastException was unhandled by user code
Message=Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'Ninject.Extensions.Conventions.Tests.IVehicleBuilderFactory`2[Ninject.Extensions.Conventions.Tests.IVehicleBuilder`1[Ninject.Extensions.Conventions.Tests.BlueBicycle],Ninject.Extensions.Conventions.Tests.BlueBicycle]'.
Source=System.Core
StackTrace:
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37
at Ninject.Extensions.Conventions.Tests.NinjectFactoryConventionsTests.VehicleBuilderFactory_Creates_Correct_Builder_For_Specified_Client() in C:\Programming\Ninject.Extensions.Conventions.Tests\NinjectFactoryConventionsTests.cs:line 40
InnerException:
Is it possible to bind using the ToFactory() method and custom provider, using the factory method argument ("Germany") along with the generic type argument (IVehicleBiulder<BlueBicycle>, BlueBicycle) to resolve the type?
Here's the rest of the code for the test, as compact and readable as I could make it.
public interface IVehicleBuilderFactory<T, TVehicle>
where T : IVehicleBuilder<TVehicle> where TVehicle : IVehicle
{
T Create<T>(string country);
}
VehicleBuilder implementations
public interface IVehicleBuilder<T> where T : IVehicle { T Build(string localizedColor); }
abstract class BicycleBuilder<T> : IVehicleBuilder<T> where T : Bicycle
{
public abstract T Build(string localizedColor);
}
public abstract class RedBicycleBuilder : IVehicleBuilder<RedBicycle>
{
private readonly RedBicycle _Bicycle;
public RedBicycleBuilder(RedBicycle Bicycle) { _Bicycle = Bicycle; }
public RedBicycle Build(string localizedColor)
{
_Bicycle.Color = localizedColor;
return _Bicycle;
}
}
public abstract class GreenBicycleBuilder : IVehicleBuilder<GreenBicycle>
{
private readonly GreenBicycle _Bicycle;
public GreenBicycleBuilder(GreenBicycle Bicycle) { _Bicycle = Bicycle; }
public GreenBicycle Build(string localizedColor)
{
_Bicycle.Color = localizedColor;
return _Bicycle;
}
}
public abstract class BlueBicycleBuilder : IVehicleBuilder<BlueBicycle>
{
private readonly BlueBicycle _Bicycle;
public BlueBicycleBuilder(BlueBicycle Bicycle) { _Bicycle = Bicycle; }
public BlueBicycle Build(string localizedColor)
{
_Bicycle.Color = localizedColor;
return _Bicycle;
}
}
public class RedBicycleBuilder_USA : RedBicycleBuilder {
public RedBicycleBuilder_USA(RedBicycle Bicycle) : base(Bicycle) { }
}
public class RedBicycleBuilder_Germany : RedBicycleBuilder {
public RedBicycleBuilder_Germany(RedBicycle Bicycle) : base(Bicycle) { }
}
public class RedBicycleBuilder_France : RedBicycleBuilder {
public RedBicycleBuilder_France(RedBicycle Bicycle) : base(Bicycle) { }
}
public class RedBicycleBuilder_Default : RedBicycleBuilder {
public RedBicycleBuilder_Default(RedBicycle Bicycle) : base(Bicycle) { }
}
public class GreenBicycleBuilder_USA : GreenBicycleBuilder {
public GreenBicycleBuilder_USA(GreenBicycle Bicycle) : base(Bicycle) { }
}
public class GreenBicycleBuilder_Germany : GreenBicycleBuilder {
public GreenBicycleBuilder_Germany(GreenBicycle Bicycle) : base(Bicycle) { }
}
public class GreenBicycleBuilder_France : GreenBicycleBuilder {
public GreenBicycleBuilder_France(GreenBicycle Bicycle) : base(Bicycle) { }
}
public class GreenBicycleBuilder_Default : GreenBicycleBuilder {
public GreenBicycleBuilder_Default(GreenBicycle Bicycle) : base(Bicycle) { }
}
public class BlueBicycleBuilder_USA : BlueBicycleBuilder
{
public BlueBicycleBuilder_USA(BlueBicycle Bicycle) : base(Bicycle) { }
}
public class BlueBicycleBuilder_Germany : BlueBicycleBuilder {
public BlueBicycleBuilder_Germany(BlueBicycle Bicycle) : base(Bicycle) { }
}
public class BlueBicycleBuilder_France : BlueBicycleBuilder
{
public BlueBicycleBuilder_France(BlueBicycle Bicycle) : base(Bicycle) { }
}
public class BlueBicycleBuilder_Default : BlueBicycleBuilder
{
public BlueBicycleBuilder_Default(BlueBicycle Bicycle) : base(Bicycle) { }
}
Vehicle implementations:
public interface IVehicle { string Color { get; set; } }
public abstract class Vehicle : IVehicle { public string Color { get; set; } }
public abstract class Bicycle : Vehicle { }
public class RedBicycle : Bicycle { }
public class GreenBicycle : Bicycle { }
public class BlueBicycle : Bicycle { }
Based on comments from #LukeN, I've refactored the Bicycle class, so that its color is set through constructor injection with an IColorSetter. The IColorSetter implementation has a generic Color type, and each of the Color implementations are 'localized' by way of constructor injection with an IColorLocalizer<T>.
This way, no class seems to have knowledge of anything beyond what is logically its responsibility (I think).
However, I'll need to think about this more to see how the refactored classes shown below can be used to show how to use a Ninject custom instance provider could be used to pick the property IColorLocalizer<T> now, since it's the only class that will know about colors and languages; the color coming from its generic type, and the language coming from the name of the implementation itself.
Since asking the original post, I've moved away from using an IoC container to make choices like this, choosing instead to programmatically put in code a switch for picking an implementation, with a default implementation selected for any unhandled outlier cases. But I'm not sure if it's mainly to get beyond something that's stumped me, or because it's a poor choice to lean on an IoC container in this way.
I'll need to update this answer more as I think about it.
Vehicles
public abstract class Vehicle {
public abstract string Color { get; internal set; }
public abstract string Move();
}
public class Bicycle : Vehicle {
public Bicycle(IColorSetter colorSetter) { colorSetter.SetColor(this); }
public override string Color { get; internal set; }
public override string Move() { return "Pedaling!"; }
}
Color setters
public interface IColorSetter { void SetColor(Vehicle vehicle); }
public class ColorSetter<T> : IColorSetter where T : Color
{
private readonly T _color;
public ColorSetter(T color) { _color = color; }
public void SetColor(Vehicle vehicle) { vehicle.Color = _color.Name; }
}
Color localizers
public interface IColorLocalizer<in T> where T : Color {
void LocalizeColor(T color);
}
public class GermanBlueLocalizer : IColorLocalizer<Blue> {
public void LocalizeColor(Blue color) { color.Name = "blau"; }
}
public class EnglishBlueLocalizer : IColorLocalizer<Blue> {
public void LocalizeColor(Blue color) { color.Name = "blue"; }
}
Colors
public abstract class Color { public string Name { get; internal set; } }
public class Red : Color {
public Red(IColorLocalizer<Red> colorLocalizer) {
colorLocalizer.LocalizeColor(this); }
}
public class Green : Color {
public Green(IColorLocalizer<Green> colorLocalizer) {
colorLocalizer.LocalizeColor(this); }
}
public class Blue : Color {
public Blue(IColorLocalizer<Blue> colorLocalizer) {
colorLocalizer.LocalizeColor(this); }
}

creating NHibernate repositories in view models with IoC

I would like to how to correct build and handle with NHibernate repository and session in view models classes.
For example I use Caliburn Micro framework with Castle Windsor boostraper.
First I created NHibernate repository:
public interface IRepository{//I omitted not needed code for simplification}
public class NHibRepository: IRepository
{
private ISession _session;
public NHibRepository(ISession session)
{
_session=session;
}
// I omitted not needed code for simplification
}
Second I definied some POCO class and mapping class with Fluent NHibernate.
public class User{}
public class Profile{}
public class Album{}
public class UserMap : ClassMap<User>{}
public class ProfileMap : ClassMap<Profile>{}
public class AlbumMap : ClassMap<Album>{}
Now I need use NHibernate repositories in my view models.
public interface IViewModelA{}
public class ViewModelA : ScreenViewModel, IViewModelA
{
public NHibRepository<User> UserRepo{get;set;}
public NHibRepository<Profile> ProfileRepo{get;set;}
}
public interface IViewModelB{}
public class ViewModelB : Screen, IViewModelB
{
public NHibRepository<Profile> ProfileRepo{get;set;}
public NHibRepoistory<Album> AlbumRepo{get;set;}
}
When I am creating repository class for some entity class I need pass session to NHibRepository construtor.
UserRepo= new NHibRepository<User>(NHIBERNATE SESSION);
Until now I used some helper class for creating Nhibernate session and init repository.
Helper class is here:
public class FluentNHibHelper
{
private ISessionFactory _sessionFactory;
public FluentNHibHelper(IPersistenceConfigurer db, Assembly asm)
{
InitializeSessionFactory(db, asm);
}
private void InitializeSessionFactory(IPersistenceConfigurer db, Assembly asm)
{
_sessionFactory = Fluently.Configure()
.Database(db)
.Mappings(m => m.FluentMappings.AddFromAssembly(asm))
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true))
.BuildSessionFactory();
}
public ISession OpenSession()
{
return _sessionFactory.OpenSession();
}
}
with this class I created repository class:
private const string ConnString =
#"Server=TestMachine\SQLEXPRESS;Database=TEST;Trusted_Connection=True;";
UserRepo = new NHibRepository<User>(
new FluentNHibHelper(MsSqlConfiguration.MsSql2008.ConnectionString(ConnString),
Assembly.GetExecutingAssembly())
.OpenSession());
Now I am confuse I don’t what is the best way for creating repository object in view models.
For example in bootstraper class can I somehow register repository class ?
public class CastleBootstrapper : Bootstrapper<IShellViewModel>
{
private IWindsorContainer _windsorContainer;
protected override void Configure()
{
_windsorContainer = new WindsorContainer();
//register repository class here ???
}
}
Can anybody help me? Thank you very much
Sorry for my english.
I use the following in an ASP.net MVC application. Castle.Windsor takes care of creating the ISession dependency for each repository.
//Located in your application startup
protected IWindsorContainer CreateContainer()
{
container = new WindsorContainer();
container.Install(
new PersistenceInstaller(),
new RepositoryInstaller()
//, other installers here
);
return container;
}
public class PersistenceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<PersistenceFacility>();
}
}
public class PersistenceFacility : AbstractFacility
{
protected override void Init()
{
NHibernate.Cfg.Configuration config = BuildDatabaseConfiguration();
Kernel.Register(
Component.For<ISessionFactory>()
.UsingFactoryMethod(config.BuildSessionFactory),
Component.For<ISession>()
.UsingFactoryMethod(k => k.Resolve<ISessionFactory>().OpenSession())
.LifeStyle.Trasient
);
}
private NHibernate.Cfg.Configuration BuildDatabaseConfiguration()
{
return Fluently.Configure()
.Database(SetupDatabase)
.Mappings(m => m.HbmMappings.AddFromAssemblyOf<Entity>())
.ExposeConfiguration(ConfigurePersistence)
.BuildConfiguration();
}
protected virtual IPersistenceConfigurer SetupDatabase()
{
return MsSqlConfiguration.MsSql2008
.UseOuterJoin()
.ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
.ShowSql();
}
protected virtual void ConfigurePersistence(NHibernate.Cfg.Configuration config)
{
SchemaMetadataUpdater.QuoteTableAndColumns(config);
}
protected virtual bool IsDomainEntity(Type t)
{
return typeof(DomainBase).IsAssignableFrom(t);
}
}
public class RepositoryInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Find().Configure(ConfigureLifeStyle()));
}
private ConfigureDelegate ConfigureLifeStyle()
{
return c => c.LifeStyle.Transient;
}
private BasedOnDescriptor Find()
{
return AllTypes.FromAssemblyContaining<NHRepository>()
.Where(type => type.Name.EndsWith("Repository"))
.WithService
.AllInterfaces();
}
}