Singleton per string ctor parameter value, for both class A and dependent class B instances - autofac

I need to create a single instance, not based on the type or a lifetime scope decl, but on the value of a string parameter to the ctor. I also need this same effect for a dependent instance of another class, using the same string in its own unrelated ctor.
class A {
public A(string appId, B b) {}
}
class B {
public B(string appId) {}
}
In the above example, I need to create an A singleton and a B singleton, for unique values of appId.
I can resolve A and B with a TypedParameter, but the singleton-per-appId-value part I can't figure out. I tried just A alone to simplify (without dependent B involved). I looked at Keyed, Indexed, etc in the docs but none seemed to fit singleton-per-some-user-defined-key-value, unless I write my own Register lambda that uses my own memory cache of unique appId keys.
Does Autofac have a built-in terse way to enforce this?

There is not going to be a good solution to this because dependency injection is generally based on types, not parameter values. It's not the same as, say, setting up caching for a web app based on parameter values. More specifically, Autofac does not have anything "baked in" that will help you. (Nor, to my knowledge, does any other DI framework.)
Likely what you're going to need to do is create a tiny factory that does the caching for you and use that.
Here's an example that I'm not compiling and not testing but is coming off the top of my head to get you unblocked.
First, you'd need to create a little factory for your B class.
public class BFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
public B GetB(string appId)
{
return this._cache.GetOrAdd(
appId,
a => new B(a));
}
}
Now you'll register BFactory as singleton, which will get you the one-instance-per-app-ID behavior you want. Register B as a lambda and it can use parameters.
builder.RegisterType<BFactory>().SingleInstance();
builder.Register((c, p) =>
{
var appId = p.Named<string>("appId");
var factory = c.Resolve<BFactory>();
return factory.GetB(appId);
});
Now you can resolve a B as long as there's a parameter passed to Resolve, like
using var scope = container.BeginLifetimeScope();
var b = scope.Resolve<B>(new NamedParameter("appId", "my-app-id"));
You can build something similar for A, but the AFactory can take a BFactory as a parameter so it can get the right instance of A.
public class AFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
private readonly BFactory _factory;
public AFactory(BFactory factory)
{
this._factory = factory;
}
public A GetA(string appId)
{
return this._cache.GetOrAdd(
appId,
a => new A(a, this._factory.GetB(a)));
}
}
Same thing here, register the factory as a singleton and get A from the factory.
builder.RegisterType<AFactory>().SingleInstance();
builder.Register((c, p) =>
{
var appId = p.Named<string>("appId");
var factory = c.Resolve<AFactory>();
return factory.GetA(appId);
});
You can get fancy with it, too, like using the Func relationships if there are some things that need to come from the container. For example, let's say your B class really looks like this:
public class B
{
public B(string appId, IComponent fromContainer) { /* ... */ }
}
In there, maybe IComponent needs to come from the container but the appId comes from a parameter. You could make the BFactory be like this:
public class BFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
private ILifetimeScope _scope;
public BFactory(ILifetimeScope scope)
{
// This will be the CONTAINER / root scope if BFactory
// is registered as a singleton!
this._scope = scope;
}
public B GetB(string appId)
{
return this._cache.GetOrAdd(
appId,
a => {
// Auto-generated factory! It will get IComponent from
// the container but let you put the string in as a parameter.
var func = this._scope.Resolve<Func<string, B>>();
return func(a);
});
}
}
Be aware if you use that auto-generated factory thing (the Func<string, B> thing) that you will need to register B by itself, like:
// You can't register the factory as the provider for B
// because it's cyclical - the BFactory will want to resolve
// a Func<string, B> which, in turn, will want to execute the
// BFactory.
builder.RegisterType<B>();
builder.RegisterType<BFactory>().SingleInstance();
That means you'd have to switch your code around to take a BFactory instead of a B. You can probably monkey with it to make it work, but you get the idea - you're going to have to make the caching mechanism yourself and that's what you'll hook into Autofac. Hopefully the above snippets can give you some ideas you can expand on and get you unblocked.

Related

Dart - Way to access a inherited static property from a parent class method

In PHP there is a way of accessing a static property value that is defined/overridden on an inheritor.
e.g.
class Foo {
public static $name='Foo';
public function who(){
echo static::$name;//the static operator
}
}
class Bar extends Foo {
public static $name='Bar';
}
$bar = new Bar();
$bar->who();
//Prints "Bar";
Is there ANY way of doing the exact same thing in Dart language?
Addressing comments:
About making it instance prop/method: There's a reason for the existence of static properties and methods and it's not having to create a new instance of the object to access a value or functionality that is not mutable.
Yes, but that's not how you are using it. Your use case is to invoke the method on an object, and therefore you really want an instance method. Now, some languages automatically allow invoking class methods as instance methods, and I see two choices for a language that offers that ability:
Statically transform fooInstance.classMethod() to ClassFoo.classMethod() based on the declared type (not the runtime type) of the object. This is what Java and C++ do.
Implicitly generate virtual instance methods that call the class method. This would allow fooInstance.classMethod() to invoke the appropriate method based on the runtime type of the object. For example, given:
class Foo {
static void f() => print('Foo.f');
}
You instead could write:
class Foo {
static void classMethod() => print('Foo.f');
final instanceMethod = classMethod;
}
and then you either could call Foo.classMethod() or Foo().instanceMethod() and do the same thing.
In either case, it's syntactic sugar and therefore isn't anything that you couldn't do yourself by being more verbose.
About the "meaning of static" and "only work because they allow invoking class methods as instance methods" : That affirmation is actually wrong. In the case of PHP, as per the example above, the Language is providing a way to access the TYPE of the class calling the method in the inheritance chain. A(methodA) >B > C. When C calls methodA, PHP allows you to know that the class type you're in is indeed C, but there's no object instance attached to it. the word "static" there is a replacement for the caller class type itself
All of that is still known at compilation time. That C derives from B derives from A is statically known, so when you try to invoke C.methodA, the compiler knows that it needs to look for methodA in B and then in A. There's no dynamic dispatch that occurs at runtime; that is still compile-time syntactic sugar. That is, if you wanted, you could explicitly write:
class A {
static void methodA() {}
}
class B extends A {
static void methodA() => A.methodA();
}
class C extends B {
static void methodA() => B.methodA();
}
Anyway, in your example, you could write:
class Foo {
static String name = 'Foo';
String get nameFromInstance => name;
void who() {
print(nameFromInstance);
}
}
class Bar extends Foo {
static String name = 'Bar';
#override
String get nameFromInstance => name;
}
void main() {
var bar = Bar();
bar.who(); // Prints: Bar
}

How can I register a (boundless) type hierarchy using Autofac?

I've got a Factory interface (along with concrete implementations):
// foo.dll
interface IFooProvider
{
T GetFoo<T>()
where T : BaseFoo;
}
My BaseFoo is not abstract, but only its subclasses are actually useful:
// shared.dll
class BaseFoo
{ ... }
I've also got a (potentially unbounded) number of subclasses of BaseFoo across many assemblies:
// foo.dll
class AFoo : BaseFoo
{ ... }
// foo2.dll
class BFoo : BaseFoo
{ ... }
... and many more ...
Naively, I had been registering the Foo-derived classes in an unsurprising way:
// foo.dll
class ConcreteFooRegistration : Module
{
protected override void Load(ContainerBuilder builder)
{
// a concrete FooProvider is registered elsewhere
builder.Register(c => c.Resolve<IFooProvider>().GetFoo<AFoo>());
builder.Register(c => c.Resolve<IFooProvider>().GetFoo<BFoo>());
...
}
}
But this implies that:
the assembly containing ConcreteFooRegistration (e.g. foo.dll) also contains some/all of AFoo, BFoo, etc.
the assembly containing ConcreteFooRegistration (e.g. foo.dll) references the assemblies (e.g. foo2.dll) containing some/all of AFoo, BFoo, etc.
IFooProvider be available to any other assembly containing BaseFoo-derived classes and the Module that registers them
For sake of discussion, assume that none of these is possible and/or desirable. That is, I'm looking for solutions other than "move IFooProvider into shared.dll".
Since AFoo and BFoo are the real dependencies that other types are interested in, and IFooProvider is (from that perspective) just an instantiation detail, I got inspired by the Autofac+Serilog integration that Nicholas came up with. I've used a similar approach elsewhere, so I wrote up an AttachToComponentRegistration() implementation:
// foo.dll
class ConcreteFooRegistration : Module
{
// NOTICE: there's no Load() method
protected override void AttachToComponentRegistration(...)
{
...
registration.Preparing += (sender, e) =>
{
var pFoo = new ResolvedParameter(
(p, i) => p.ParameterType.IsAssignableTo<BaseFoo>(),
(p, i) => i.Resolve<IFooProvider>().GetFoo<FooWeNeed>()
);
e.Parameters = new [] { pFoo }.Concat(e.Parameters);
};
}
}
This was successful, in that I was able to remove all the individual BaseFoo-derived registrations from ConcreteFooRegistration and still successfully resolve arbitrary BaseFoo-derived dependencies with constructor injection:
// other.dll:
class WorkerRegisteration : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Worker>();
// NOTICE: FooYouDidntKnowAbout is NOT explicitly registered
}
}
class Worker
{
public Worker(FooYouDidntKnowAbout foo)
{ ... }
...
}
BUT: now I can't arbitrarily resolve AFoo outside of constructor injection:
builder.Register(c =>
{
// here's one use for a BaseFoo outside constructor injection
var foo = c.Resolve<AFoo>();
if (foo.PropValue1)
return new OtherClass(foo.PropValue2);
else
return new YetAnother(foo.PropValue3);
}
...
builder.Register(c =>
{
// here's another
var foo = c.Resolve<AFoo>();
return c.Resolve(foo.TypePropValue);
});
Assuming that publishing IFooProvider as a public export of foo.dll or moving it to shared.dll is undesirable/impossible, thus eliminating the naive-but-unsurprising implementation above, (how) can I set up my registrations to be able to resolve arbitrary subclasses of BaseFoo from anywhere?
Thanks!
I think what you're looking for is a registration source. A registration source is a dynamic "registration provider" you can use to feed Autofac registrations as needed.
As of this writing, the doc on registration sources is pretty thin (I just haven't gotten a chance to write it) but there's a blog article with some details about it.
Registration sources are how Autofac supports things like IEnumerable<T> or Lazy<T> - we don't require you actually register every collection, instead we dynamically feed the registrations into the container using sources.
Anyway, let me write you up a sample here and maybe I can use it later to massage it into the docs, eh? :)
First, let's define a very simple factory and implementation. I'm going to use "Service" instead of "Foo" here because my brain stumbles after it sees "foo" too many times. That's a "me" thing. But I digress.
public interface IServiceProvider
{
T GetService<T>() where T : BaseService;
}
public class ServiceProvider : IServiceProvider
{
public T GetService<T>() where T : BaseService
{
return (T)Activator.CreateInstance(typeof(T));
}
}
OK, now let's make the service types. Obviously for this sample all the types are sort of in one assembly, but when your code references the type and the JIT brings it in from some other assembly, it'll work just the same. Don't worry about cross-assembly stuff for this.
public abstract class BaseService { }
public class ServiceA : BaseService { }
public class ServiceB : BaseService { }
Finally, a couple of classes that consume the services, just so we can see it working.
public class ConsumerA
{
public ConsumerA(ServiceA service)
{
Console.WriteLine("ConsumerA: {0}", service.GetType());
}
}
public class ConsumerB
{
public ConsumerB(ServiceB service)
{
Console.WriteLine("ConsumerB: {0}", service.GetType());
}
}
Good.
Here's the important bit, now: the registration source. The registration source is where you will:
Determine if the resolve operation is asking for a BaseService type or not. If it's not, then you can't handle it so you'll bail.
Build up the dynamic registration for the specific type of BaseService derivative being requested, which will include the lambda that invokes the provider/factory to get the instance.
Return the dynamic registration to the resolve operation so it can do the work.
It looks like this:
using Autofac;
using Autofac.Core;
using Autofac.Core.Activators.Delegate;
using Autofac.Core.Lifetime;
using Autofac.Core.Registration;
public class ServiceRegistrationSource : IRegistrationSource
{
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service,
Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if(swt == null || !typeof(BaseService).IsAssignableFrom(swt.ServiceType))
{
// It's not a request for the base service type, so skip it.
return Enumerable.Empty<IComponentRegistration>();
}
// This is where the magic happens!
var registration = new ComponentRegistration(
Guid.NewGuid(),
new DelegateActivator(swt.ServiceType, (c, p) =>
{
// The factory method is generic, but we're working
// at a reflection level, so there's a bit of crazy
// to deal with.
var provider = c.Resolve<IServiceProvider>();
var method = provider.GetType().GetMethod("GetService").MakeGenericMethod(swt.ServiceType);
return method.Invoke(provider, null);
}),
new CurrentScopeLifetime(),
InstanceSharing.None,
InstanceOwnership.OwnedByLifetimeScope,
new [] { service },
new Dictionary<string, object>());
return new IComponentRegistration[] { registration };
}
public bool IsAdapterForIndividualComponents { get{ return false; } }
}
It looks complex, but it's not too bad.
The last step is to get the factory registered as well as the registration source. For my sample, I put those in an Autofac module so they're both registered together - it doesn't make sense to have one without the other.
public class ServiceProviderModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ServiceProvider>().As<IServiceProvider>();
builder.RegisterSource(new ServiceRegistrationSource());
}
}
Finally, let's see it in action. If I throw this code into a console app...
static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<ConsumerA>();
builder.RegisterType<ConsumerB>();
builder.RegisterModule<ServiceProviderModule>();
var container = builder.Build();
using(var scope = container.BeginLifetimeScope())
{
var a = scope.Resolve<ConsumerA>();
var b = scope.Resolve<ConsumerB>();
}
}
What you end up with on the console is:
ConsumerA: ServiceA
ConsumerB: ServiceB
Note I had to register my consuming classes but I didn't explicitly register any of the BaseService-derived classes - that was all done by the registration source.
If you want to see more registration source samples, check out the Autofac source, particularly under the Autofac.Features namespace. There you'll find things like the CollectionRegistrationSource, which is responsible for handling IEnumerable<T> support.

does AutoMoqCustomization work for abstract classes?

Please note, I'm somewhat new to TDD, so I will take general advice as well as specific answer.
Neither abstract classes nor interfaces can be instantiated. Clearly Moq can give me a mocked up instance of the ADataFeed in the second test. Why does AutoMoqCustomization work for interfaces IDataFeed but not for abstract classes ADataFeed, instead throwing an InvalidOperationException?
Secondarily, what would be the AutoFixture approach (or TDD generally) be to drive a design that might call for an abstract class with a constructor to require and guarantee certain values, such as a connection string in this case?
[Theory, AutoMoqData]
public void AllDataFeedsHaveAConectionString(
IDataFeed sut)
{
var result = sut.GetConnectionString();
Assert.Null(result);
}
[Fact]
public void AllDataFeedsRequireAConnectionString()
{
var expected = Guid.NewGuid().ToString();
var sut = new Mock<ADataFeed>(expected);
var result = sut.Object.GetConnectionString();
Assert.Equal(expected, result);
}
[Theory, AutoMoqData]
public void AllDataFeedsRequireAConnectionString2(
[Frozen] string expected,
ADataFeed sut)
{
var result = sut.GetConnectionString();
Assert.Equal(expected, result);
}
Abstract classes with constructors must be marked protected. AutoFixture will not program against abstract classes when the constructor is marked public, as this is a design error.

autofac: IEnumerable<Lazy<IFoo, IFooMetaData>> --> Lazy.Value(with runtime param)?

Using Autofac, I have multiple IFoo components that take a run-time parameter in the constructor. I'm using some Metadata from the types along with the run-time parameter to construct and manage running instances.
interface IFoo
{
int RunTimeId { get; }
}
[FooMeta("ShaqFoo")]
class Foo1 : IFoo
{
public Foo1 (int runtTimeId)
{
...
}
[FooMeta("KungFoo")]
class Foo2 : IFoo
{
public Foo2 (int runtTimeId)
{
...
}
Module/Registration something like:
builder.Register<Func<int, Foo1>>(c =>
{
var cc = c.Resolve<IComponentContext>();
return id => cc.Resolve<Foo1>(TypedParameter.From<int>(id));
})
.As<Func<int, IFoo>>()
.WithMetadata<IFooMetaData>(m => m.For(sm => sm.FooType, typeof(Foo1)));
builder.Register<Func<int, Foo2>>(c =>
{
var cc = c.Resolve<IComponentContext>();
return id => cc.Resolve<Foo2>(TypedParameter.From<int>(id));
})
.As<Func<int, IFoo>>()
.WithMetadata<IFooMetaData>(m => m.For(sm => sm.FooType, typeof(Foo2)));
And a component that creates new Foos with the run-time parameters and metadata. I need to be create ALL IFoos for a given run-time parameter, and need to check for existing instances (essentially using Metadata + RunTimeId as a key) before creating.
public class FooActivator
{
public FooActivator(IEnumerable<Lazy<Func<int, IFoo>, IFooMetaData>> fooFactories)
{
m_FooFactories = fooFactories;
}
private void HandleNewRunTimeIdEvent(int id)
{
CreateFoosForNewId(id);
}
private void CreateFoosForNewId(int id)
{
foreach (var fooFactory in m_FooFactories)
{
if (!FooWithThisMetadataAndIdExists(fooFactory.Metadata.FooType, id))
{
var newFoo = fooFactory.Value(id);
}
}
}
}
Obviously, I can enumerate all of the IFoos and check metadata using the Lazy Enumeration, but can't pass in the run-time parameter to Lazy.Value. Seems like I need to pass in an Enumerable of Func<>s somehow, but can't figure out how to attach the metadata. Or maybe I need an entirely different approach?
Just getting my head wrapped around autofac, and hoping there's a clean way to accomplish this. I could settle for just using the concrete Foo type (instead of metadata) if there's a simple way to enumerate all of them (without creating them), and use the type + run-time Id as my key instead.
Updated the code with a working solution. Figured out how to register Factories properly with metadata. Seems to work.

Using Verify to confirm expected parameter values in Moq mock class

I'm trying to verify that a method within a mock is called with an expected object parameter. I'm using Moq, nUnit, and thinking that AutoFixture's Likeness should get the job done.
Below is a simplified version of what i'm trying to do.
Is there a way to do this with AutoFixture? Is there a better way to verify that Something is called with the appropriate parameter?
Overriding Equals in the A class to compare the property values and changing the Verify line to:
barMock.Verify(m => m.Something(a));
passes, however I'd rather not override Equals in every class like A in my project.
namespace Test
{
using Moq;
using NUnit.Framework;
using Ploeh.SemanticComparison.Fluent;
public class A
{
public int P1 { get; set; }
}
public interface IBar
{
void Something(A a);
}
public class Foo
{
public A Data { get; private set; }
public void DoSomethingWith(IBar bar)
{
Data = new A { P1 = 1 };
bar.Something(Data);
}
}
[TestFixture]
public class AutoFixtureTest
{
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var a = new A { P1 = 1 };
var expectedA = a.AsSource().OfLikeness<A>();
foo.DoSomethingWith(barMock.Object);
expectedA.ShouldEqual(foo.Data); // passes
barMock.Verify(m => m.Something(expectedA.Value)); // fails
}
}
}
In Verify Moq by default checks reference equality for arguments so it only passes when you provide the same instances (except if you've overriden Equals) in your tests and in your implementation.
In you case the expectedA.Value just returns the new A { P1 = 1 } created in the test which, of course, isn't the same instance created in DoSomethingWith.
You need to use Moq's It.Is construct to properly test this without overriding Equals (in fact for this you don't need Autofixture at all):
barMock.Verify(m => m.Something(It.Is<A>(arg => arg.P1 == a.P1)));
But if you have multiple properties like P1,P2,P3... AutoFixture can be useful:
barMock.Verify(m => m.Something(It.Is<A>(arg => expectedA.Equals(a))));
Because you don't need to write out the equality checks manually for all the properties.
If you upgrade to AutoFixture 2.9.1 (or newer) you can call the CreateProxy method on the Likeness instance which will emit a dynamic proxy for the destination type.
The generated dynamic proxy overrides Equals using Likeness which simplifies the syntax (quite a lot).
Here is the original test method, modified to use the Likeness proxy:
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var expected = new A().AsSource().OfLikeness<A>().CreateProxy();
expected.P1 = 1;
foo.DoSomethingWith(barMock.Object);
Assert.True(expected.Equals(foo.Data)); // passes
barMock.Verify(m => m.Something(expected)); // passes
}
Note that it also makes the test assertion much more specific than accepting Any instance.
You can find more details on this new feature here.