Построение компонента Autofac на основе параметров ctor - PullRequest
2 голосов
/ 19 августа 2011

Можно ли зарегистрировать компоненты таким образом, чтобы они могли быть разрешены на основе параметров конструктора?

public interface IRepository<T>{}
public interface IMyRepo {}

public class MyRepo : IRepository<TEntity>, IMyRepo
{
    public MyRepo(IDbConnection connection){}
    public MyRepo(){}
}

// lots of other repositories...

public class Global
{
    public void BuildDIContainer()
    {
        var builder = new ContainerBuilder();
        var assembly = Assembly.GetExecutingAssembly();

        //any class that implements IRepository<T> is instance per request
        builder.RegisterAssemblyTypes(typeof (IRepository<>).Assembly, assembly)
            .AsClosedTypesOf(typeof (IRepository<>))
            .AsImplementedInterfaces().InstancePerHttpRequest();

        //any class that implements IRepository<T> with IDbConnection as ctor parameter is instance per dependency
        builder.RegisterAssemblyTypes(typeof(IRepository<>).Assembly, assembly)
            .UsingConstructor(typeof(IDbConnection)) // <-- ??
          .AsClosedTypesOf(typeof(IRepository<>))
          .AsImplementedInterfaces().InstancePerDependency();

        //............

        //per dependency
        var repo1 = ComponentContext.Resolve<IMyRepo>(new NamedParameter("connection", new SqlConnection("...")));
        //per request
        var repo2 = ComponentContext.Resolve<IMyRepo>();
    }
}

1 Ответ

5 голосов
/ 21 августа 2011

Зарегистрируйте MyRepo только один раз, используя .InstancePerLifetimeScope().

Это будет эквивалентно .InstancePerHttpRequest() при использовании в веб-приложении (я предполагаю, что в этом случае вместо вызова Resolve() сбез параметра, вы просто берете зависимость, которая вводится.)

Затем вместо разрешения IMyRepo непосредственно при передаче параметра разрешите Owned<IMyRepo>:

using (var repoWithParam = ComponentContext.Resolve<Owned<IMyRepo>>(
    new NamedParameter("connection", ...))){
    // Use repoWithParam.Value here
}

Этобудет иметь дополнительное преимущество, заключающееся в том, что ваш репозиторий, разрешенный с помощью настраиваемого соединения, будет выпущен правильно.

Надеюсь, это поможет, сделав несколько предположений о вашем сценарии, поэтому дайте мне знать, если что-то неясно.

...