Autofac Generic Service Runtime Permission

Castle recently added support for front-end factories with kernel-provided implementations. I am wondering if there is a way to do this in autofac as well. I read about delegate factories, but I think that maybe something is missing and I cannot get it to work. That's what I think:

class Message { }

interface IHandle<T> {
    void Handle(T message);
}

class Handle<Message> : IHandle<Message> {
    ...
}

class Bus {
    .ctor (? lookup) {
        _lookup = lookup;
    }

    void Send<T>(T message) {
        _lookup.GetHandler<T>().Handle(message);
    }
}

var builder = new ContainerBuilder();
builder.RegisterType<Handle<Message>>().As<IHandle<Message>>();
builder.RegisterType<Bus>();

var container = builder.Build();
container.Resolve<Bus>().Send<Message>(new Message());

I am trying to make a container from the bus (since I agree that the service locator is an anti-pattern) or any other implementation. This problem is simple if I just load the container onto the bus or create a factory class that wraps the container. Just trying to make sure there is no way to do this.

Btw, the iirc lock path allows me to register something like this:

interface IHandlerFactory {
    IHandle<T> GetHandler<T>();
}

container.Register<IHandlerFactory>().AsFactory();

Thanks Nick

+2
source share
2

, IHandlerFactory, AutofacHandlerFactory, ILifetimeScope. , , IHandler<T>.

ILifetimeScope , IHandlerFactory, Bus . , Ninject, NinjectHandlerFactory .

+4

, "".

AggregateService, , , factory "" Castle.Proxies.IComponentFactoryProxy " " DynamicProxyGenAssembly2, Version = 0.0.0.0, Culture = neutral, PublicKeyToken = null " ". ( , ).

, ( ) . , .

, :

public class Bus {
  readonly ILifetimeScope _OwnScope;

  // Autofac always provides ILifetimeScope that owns a component as a service to the component
  // so it can be used as a dependency
  public Bus(ILifetimeScope ownScope) {
    _OwnScope = ownScope;
  }

  void Send<T>(T message) {
    _OwnScope.Resolve<IHandler<T>>.Handle(message);
  }
}

, , , ILifetimeScope - . , , . factory. , , , .

+4

All Articles