Search code examples
c#dependency-injectionautofac

Property of one class is passed as parameter to constructor of another class. How to resolve this with Autofac?


I am new with Autofac and this is scenario of my problem:

I have 2 classes, both of them are singletons.

One of them has some public property, eg.

public class ClassWithProperty
{
  public string SomeProperty { get; set; }
}

and the second class has a constructor which should take a property from first class as parameter:

public class ClassWithConstructor
  {
    private string _someParameter;

    public ClassWithConstructor(string someParameter)
    {
      _someParameter = someParameter;
    }
  }

without Autofac I can just do it like this:

var classWithProperty = new ClassWithProperty();
var classWithConstructor = new ClassWithConstructor(classWithProperty.SomeProperty);

I cannot resolve this problem with Autofac and find any solution here or in google. What I do:

var builder = new ContainerBuilder();

builder.RegisterType<ClassWithProperty>().InstancePerLifetimeScope();
builder.RegisterType<ClassWithConstructor>()
    .WithParameter() // what should be done here to pass exactly ClassWithProperty.SomeProperty here?
    .InstancePerLifetimeScope();
var container = builder.Build();

of course it is simplified scenario just to show my problem. In real scenario I pass TreeList from one form to another view class and working exactly on that TreeList.


Solution

  • You can register a lambda to manually construct your ClassWithConstructor

    var builder = new ContainerBuilder();
    
    builder.RegisterType<ClassWithProperty>()
           .InstancePerLifetimeScope();
    builder.Register(c => new ClassWithConstructor(c.Resolve<ClassWithProperty>().SomeProperty))
           .InstancePerLifetimeScope(); 
    

    or

    var builder = new ContainerBuilder();
    
    builder.RegisterType<ClassWithProperty>()
           .InstancePerLifetimeScope();
    builder.Register<ClassWithConstructor>()
           .WithParameter(new ResolvedParameter(
                  (pi, ctx) => pi.ParameterType == typeof(string) && pi.Name == "someParameter",
                  (pi, ctx) => "sectionName"))
           .InstancePerLifetimeScope();