lundi 3 avril 2017

Inject a property (recursively) without passing it as a parameter

I'm trying to achieve maybe something that might be impossible.

We have a big MVC 5 application. I created a small MVC project to simulate and explain what I want to apply into that big MVC project.

I have a controller that has unique Id. In this sample project the unique Id is regenerated for each request. In the MVC project, it is a bit more complex and different. However it's not relevant in the scope of this example.

public class FooController : Controller
{
    public string UniqueId = Guid.NewGuid().ToString("N");
    public ActionResult Index()
    {
        var worker = new WorkerA();
        worker.DoWork();
        return View();
    }
}

The FooController creates WorkerA which creates WorkerB which creates WorkerC and so on. The workers are not the same. They don't have the same interface/implementation. To make the example simple I made them look similar.

Here's the Workers:

public class WorkerA
{
    public string UniqueId = string.Empty;

    public void DoWork()
    {
        var worker = new WorkerB();
        worker.DoWork();
        //...
        //...

    }
}
public class WorkerB
{
    public string UniqueId = string.Empty;

    public void DoWork()
    {
        var worker = new WorkerC();
        worker.DoWork();
    }
}

I want to have inject the property UniqueId into the worker without having to passing it as a parameter.

I want to avoid having to do this:

public WorkerA(string uniqueId)
{
    UniqueId = uniqueId;
}

But I need to do the same for all the other workers.

Aucun commentaire:

Enregistrer un commentaire