I'm struggling to get a unit test working for one of my classes. I want to inject my factory instead of the autogenerated factory the autofac resolves to. How do I register my own function as the delegate to replace the autogenerated delegate factory?
My code looks something like this is outline form:
interface IEntryImporter { ... }
class EntryImporter : IEntryImporter {
public EntryImporter(ISeries series, IMatch match, Entry.Factory entryFactory) {
:
}
:
}
interface IEntry : { ... }
class Entry : IEntry {
public delegate IEntry Factory();
public Entry() { ... }
}
interface IMatch : { ... }
class Match : IMatch { ... }
interface ISeries : { ... }
class Series : ISeries { ... }
void IEntry MyEntryFactory() {
var entry = new Mock<IEntry>();
:
return entry.Object;
}
void TestMe() {
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Entry>().As<IEntry>();
builder.RegisterType<Match>().As<IMatch>();
builder.RegisterType<Series>().As<ISeries>();
builder.RegisterType<EntryImporter>.As<IEntryImporter>();
var series = new Mock<ISeries>(MockBehavior.Strict);
builder.RegisterInstance<ISeries>(series.Object);
var match = new Mock<IMatch>(MockBehavior.Strict);
builder.RegisterInstance<IMatch>(match.Object);
// How to register MyEntryFactory as Entry.Factory for autofac to resolve?
using(var container = builder.Build()) {
var importer = container.Resolve<IEntryImporter>();
:
}
}
You can register your own method for use as the mock entry factory as follows:
builder.Register<Entry.Factory>(c => MyEntryFactory).As<Entry.Factory>();
I have got your sample working as part of Autofac Answers on GitHub.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With