2016-12-02 3 views
0

Я пытаюсь добиться строительства объекта, как показано ниже,замок Виндзор зависимости propogating инлайн

using (var context = new DbContext()) 
{ 
    var processor = new Processor(context, new Parser(context, new Logger(context)), new Logger(context)); 
} 

но используя замок Виндзор. Я использую встроенные зависимости, как показано ниже в коде, но поскольку документация Castle Windsor гласит: «Внутренние зависимости не распространяются» Castle Windsor passing arguments. Как я могу добиться этого другим способом?

using Castle.MicroKernel.Registration; 
using Castle.Windsor; 
using System; 

namespace IOCTesting 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      using (var context = new DbContext()) 
      { 
       var processor = new Processor(context, new Parser(context, new Logger(context)), new Logger(context)); 
      } 

      var container = new WindsorContainer(); 

      container 
       .Register(Component.For<IProcessor>() 
       .ImplementedBy<Processor>()); 

      container 
       .Register(Component.For<IParser>() 
       .ImplementedBy<Parser>()); 

      container 
       .Register(Component.For<ILogger>() 
       .ImplementedBy<Logger>()); 


      //[1] Creating my scope object here. (context) 
      using (var context = new DbContext()) 
      { 
       var processor = container.Resolve<IProcessor>(new { context = context }); 
      } 
     } 
    } 

    public class DbContext : IDisposable 
    { 
     public void Dispose() 
     { 
      Console.WriteLine("DbContext disposed."); 
     } 
    } 

    public class Processor : IProcessor 
    { 
     private readonly DbContext _context; 
     private readonly ILogger _logger; 
     private readonly IParser _parser; 

     //Dependency context passed in is the same object within the scope. See [1] 
     public Processor(DbContext context, IParser parser, ILogger logger) 
     { 
      _context = context; 
      _parser = parser; 
      _logger = logger; 
     } 
    } 

    public class Parser : IParser 
    { 
     private readonly DbContext _context; 
     private readonly ILogger _logger; 

     //Dependency context passed in is the same object within the scope. See [1] 
     public Parser(DbContext context, ILogger logger) 
     { 
      _context = context; 
      _logger = logger; 
     } 
    } 

    public class Logger : ILogger 
    { 
     private readonly DbContext _context; 

     //Dependency context passed in is the same object within the scope. See [1] 
     public Logger(DbContext context) 
     { 
      _context = context; 
     } 
    } 

    public interface IProcessor 
    { 
    } 

    public interface IParser 
    { 
    } 

    public interface ILogger 
    { 
    } 
} 

ответ

1

Вам нужно взглянуть на область обзора; на данный момент вы не указываете область, поэтому все зависимости будут одноточечными. Зарегистрировать DBContext вместе с ILogger, IParser и IProcessor все с Scoped lifestlye. НАПРИМЕР.

container.Register(Component.For<DBContext>() 
    .ImplementedBy<DBContext>() 
    .Lifestyle.Scoped); 

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

using(container.BeginScope()) 
{ 
    var processor = container.Resolve<IProcessor>(); 
    // use processor here. 
} 

Теперь новый DBContext будет создан в рамках и утилизированы, когда объем контейнера заканчивается. Вам не нужно беспокоиться об инициализации DBContext или передаче его методу Resolve.

+0

Это работает красиво. Спасибо за это. – dezzy

 Смежные вопросы

  • Нет связанных вопросов^_^