Autofac - method implementation example

Can someone provide an example of using the all-around method using Autofac?

I checked the documentation, but it's hard for me to understand how this works and how this method is allowed.

So, ok, pretty simple, how to register everything, but how can I use it? For example, I would like to have a method that introduces HttpContext. So, having something like this:

builder
  .Register<MyObjectType>()
  .OnActivating(e => {
    var dep = new HttpContextWrapper(HttpContext.Current);
    e.Instance.SetTheDependency(dep);
  })
  .InstancePerRequest();

Note. This is possible when installing the constructor, but I would like to understand the method of method injection.

The question is how to use a permitted instance? Is it possible to use the injection method to get the result back with the method that gets the dependencies? The behavior is nowhere near the injection of the parameter, but is it somehow close to embedding the properties?

Update

@fknx , :

, , (setter)

, , ( Java), ?

, ?

+4
1

, :

using System;
using Autofac;

public class Program
{
    public static void Main()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<MyService>()
            .OnActivating(e => e.Instance.SetMyDependency(new MyDependency()));

        var container = builder.Build();
        container.Resolve<MyService>();
    }
}

public class MyService
{
    private MyDependency _myDependency;

    public void SetMyDependency(MyDependency myDependency)
    {
        _myDependency = myDependency;
        Console.WriteLine("SetMyDependency called");
    }
}

public class MyDependency
{
}

, , , Register RegisterType.

, .

. , , (setter).

.NET Fiddle, .

Update

, , ( Java)

, .

?

, , (readonly) , .

, ?

, #. , Java, setter. # .

, , , .

, , , - (, ).

+4

Source: https://habr.com/ru/post/1650524/


All Articles