Using Autofac, I have the following scenario:
public class MainClass
{
public delegate MainClass Factory();
public MainClass(Report report, SecondaryClass secClass)
{
Report=report;
SecondaryClass = secClass;
}
public Report Report {get; private set;}
public SecondaryClass SecondaryClass {get; private set;}
}
public class SecondaryClass
{
public SecondaryClass(Report report)
{
Report=report;
}
public Report Report {get; private set;}
}
What I would like to achieve is that every time I invoke the Factory() delegate on MainClass, both MainClass and SecondaryClass are injected with the same instance of Report.
Basically
public void MyMethod()
{
var myMainClass = _MainClassFactory.Invoke();
//How do I do achieve this????
Debug.Assert (object.ReferenceEquals(myMainClass.Report , myMainClass.SecondaryClass.Report));
}
How can I configure MainClass and SecondaryClass?
My current configuration is the following, but it does not seem to achieve what I want.
As a matter of fact, every time I call the Factory method, I get the same instance of Report.
builder.RegisterType<MainClass>().AsSelf();
builder.RegisterType<SecondaryClass>().AsSelf();
builder.RegisterType<Report>().AsSelf().InstancePerLifetimeScope();
As usual, it depends.
If you want to express the fact that
MainClassdeliberately requires the same instance ofReportas the instance ofSecondaryClassuses, then you should either take theReportfrom theSecondaryClassas @adrift has suggested in comments, or use parametrization:(see autofac wiki for reference)
With these approaches you directly show that you require that two objects use the same
Report.If your
SecondaryClassandMainClassdo not care if they use the sameReport, and it’s just your wish to make them share it, you could use a separate lifetime scope as @adrift has suggested. But beware that if you use other components that depend onReport, they’ll also get the same instance inside that lifetime scope. It will be kind of a singleton inside the scope.I do not recomment using lifetime scope if your components do depend on using the same instance. If you did, the requirement would be obfuscated which is bad.