Кошке
А ты подписался на rss?

Иерархический ServiceLocator

by Игорь Лизунов 21.01.2009 19:57

Кто не знает, что такое service locator (IoC, ServiceManager) — пусть идет и узнает.

У остальных, надеюсь, следующие рассуждения вызовуд согласие и одобрение.

Когда используешь IoС, постепенно он замусоревается всякой чепухой. Староверы, конечно, скажут, что его нужно использовать только для глобальных сервисов типа логгера. Однако, использовать IoC удобно и для локальных нужд, поэтому староверы идут лесом.

Те, кто хоть раз в жизни видел Smart Client Software Factory, знает, что в ней существует иерархия WorkItem'ов — это такие рабочие лошадки, на которых висит логика работы приложения. У каждого воркайтема там доступен сервис локатор, в который можно добавить свой или взять напосматреть чужой сервис. Фишка в том, что если сервис не найден в локальном сервис локаторе, он ищется в сервис локаторе родительского воркайтема.

Соответственно, в каждом воркайтеме можно а) зарегистрировать новый сервис, который будет виден только для себя и для дочерних объектов; и б) перерегистрировать (owerwrite) существующий сервис, представленный выше по иерархии.

Круты перцы все время используют эти шняги чтобы сделать логику приложения гибкой.

Также, круты перцы не понимают, почему аналогичной функциональности нету не в рамках SCSF.

Внимание, код:

   1:      class SubClass
   2:      {
   3:          public void Test()
   4:          {
   5:              Console.WriteLine(this.GetService<string>());
   6:          }
   7:          public void RegisterService()
   8:          {
   9:              this.AddService<string>("2");
  10:          }
  11:      }
  12:   
  13:      class Program
  14:      {
  15:          static void Main(string[] args)
  16:          {
  17:              new Program().Main();
  18:          }
  19:   
  20:          void Main()
  21:          {
  22:              this.AddService("1");
  23:   
  24:              Console.WriteLine(this.GetService<string>());
  25:   
  26:              SubClass child = new SubClass();
  27:   
  28:              this.AddChildWorkItem(child);
  29:   
  30:              child.Test();
  31:   
  32:              child.RegisterService();
  33:   
  34:              child.Test();
  35:   
  36:              Console.ReadLine();
  37:          }
  38:      }

 

Выводится следующее:

   1:  1
   2:  1
   3:  2

 

Итак, мы взяли объект Program, зарегистрировали глобальный сервис типа string (22). Попробовали — работает (24).

Дальше, мы добавили дочерний объект, у которого уже свой сервис локатор (28). Попробовали — показался родительский сервис (30).

И вот то, ради чего весь сыр-бор: перерегистрируем сервис и пробуем. Выводится «2», сработал уже локальный сервис(32).

Как работает? Методы на себе можно вызывать с помощью наших любимых экстеншнов.

   1:  public static TService GetService<TService>(this object owner)
   2:  {
   3:        return IoC.Instance.GetService<TService>(owner);
   4:  }

За счет этого, IoC получает доступ к объекту, вызывающему метод. Дальше все просто — внутри IoC строится и поддерживается иерархия.

Подробности - в коде.

Если кому-то хочется, чтобы я еще про что-то рассказал — добро пожаловать в каменты.

Tags: , , ,

Комментарии

21.01.2009 20:52:33 #

Павел

Идея SL интересна, особенно как альтернатива DI (Dependency Injection). В OSGi (Open Services Gateway Initiative) существует похожая концепция, только сервисы выставляются в распределенных бандлах (плагинах), но их так же можно стартовать, стопить, релоадить и т.д.

А еще есть концепция IoC-контейнеров (точнее DI-контейнеров), например Spring и Guice. Риальные пацаны скрестили ужа и ежа и создали Spring Modules - интеграцию OSGi и Spring. Получилось неплохо.

Павел | Reply

22.01.2009 7:59:28 #

ilizunov

Ну вообще в DI контейнерах обычно есть иерархия.
Тока там обычно надо, чтобы объект билдился этим контейнером

ilizunov | Reply

22.01.2009 9:46:20 #

Самолысов Павел

Ну собственно в этом и суть - чтобы билдился.

Про иерархию - в Spring на сколько я знаю ее нет (хотя может в 2.5 и появилась, не ковырял). Т.е. все бины доступны отовсюду где есть доступ к BeanFactory или ApplicationContext.

В Guice же например сделали модульность, т.е. зависимости описываются в специальном классе-модуле, и соответственно модули друг с другом не пересекаются.

Самолысов Павел | Reply

22.01.2009 22:12:11 #

Юрий

Собс-сно, почти любой DI-container можно юзать как SL (это так по кр.м. для Microkernel/Windsor и StructureMap).
Только это крутыми пацанами считается западло, т.к. увеличивает сцепление в коде. С точки зрения крутых пацанов, код должен быть в неведении (agnostic), откуда ему пришел сервис и каково его время жизни (singleton/создается на каждый вызов и пр.). Так что, как правильно отметил Паша - в этом и суть, чтобы билдился.

Юрий | Reply

03.02.2009 11:40:12 #

xelibrion

В Unity есть иерархия, подобная оной в SCSF. Да и оно не удивильно - и то, и другое поделки MS P&P.

xelibrion | Reply

22.07.2010 7:31:22 #

wow gold

Hi. I wanted to drop you a quick note to express my thanks. I've been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you've structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be.

wow gold | Reply

22.07.2010 7:52:49 #

game exchange

can someone tell me how to get those little avatars to display in my comments section? thanks!

game exchange | Reply

22.07.2010 7:55:10 #

game store

Hi. I wanted to drop you a quick note to express my thanks. I've been following your blog for a month or so and have picked up a ton of good information as well as enjoyed the way you've structured your site. I am attempting to run my own blog but I think its too general and I want to focus more on smaller topics. Being all things to all people is not all that its cracked up to be.

game store | Reply

25.07.2010 0:31:45 #

wow gold

You gave great points here. I made a research on the subject and found nearly all peoples will agree with your blog.

wow gold | Reply

25.07.2010 1:23:01 #

latest game news

Excellent read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that: Thanks for lunch!

latest game news | Reply

25.07.2010 2:31:52 #

gold4power

Dude, please tell me that youre going to write more.  I notice you havent written another blog for a while (Im just catching up myself).  Your blog is just too important to be missed.  Youve got so much to say, such knowledge about this subject it would be a shame to see this blog disappear.  The internet needs you, man!

gold4power | Reply

28.07.2010 16:56:01 #

wow gold

I hope you never stop!  This is one of the best blogs Ive ever read.  Youve got some mad skill here, man.  I just hope that you dont lose your style because youre definitely one of the coolest bloggers out there.  Please keep it up because the internet needs someone like you spreading the word.

wow gold | Reply

28.07.2010 17:30:43 #

Wow Gold Hack

I have been surfing online more than three hours today, yet I never found any interesting article like yours. It's pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the internet will be much more useful than ever before.

Wow Gold Hack | Reply

28.07.2010 18:14:46 #

chinese game news

Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.

chinese game news | Reply

02.09.2010 16:19:34 #

ff14 gil

I found a great website for us to watch free movies. I love this site and I thought that I should share,its call <A href="movies-links.cc">movies-links.cc</A> enjoy

ff14 gil | Reply

02.09.2010 17:09:59 #

Wow Gold Dupe

Have to say very good and the info is really useful. I will deffintately be back in the near future to keep up with what going on.

Wow Gold Dupe | Reply

02.09.2010 18:43:07 #

pearl necklaces

Good Morning, I am studying microwaves and am interested in temperature increases on commercial microwaves. your university has a dept i am sure. Great to see more universities blogging articles and information on the web. Would it be possible to include your blog post on one of my blogs as I have an interest in microwaves. I will of course leave a link to you blog? please email me

pearl necklaces | Reply

03.09.2010 20:20:37 #

wow curse

Considerably, the article is really the sweetest on this worthwhile topic. I harmonise with your conclusions and will eagerly look forward to your next updates. Just saying thanks will not just be sufficient, for the fantastic lucidity in your writing. I will right away grab your rss feed to stay informed of any updates. Delightful work and much success in your business endeavors!

wow curse | Reply

17.11.2010 9:30:24 #

timberland 14 inch boots

Instead, we see people with ugly timberland shoes store problems in whom God is working so they can bloom beautifully — just like I now see in my orchids whether they are “lumps” or blossoms! On a certain timberland work shoes day at a certain hour, we will pull into the station. Bands will be playing and flags waving. Once we get there, so many wonderful dreams will come true and the pieces of our timberland wheat shoes lives will fit together like a completed jigsaw puzzle. How restlessly we pace the aisles, *ing the minutes for timberland for you loitering --waiting, waiting, waiting for the station. It is a good thing that the God Who made us is not impatient with people like me with my timberland shoe company orchid. He lovingly thinks about us all the time timberland boots and he even temporarily gave up His heavenly home and his timberland traditional handsewn hold on diety to die for the sins of timberland mens custom world nearly 2,000 years ago. His death back then covered the sins of every cheap timberland boots person who will ever live. He then rose to life after three mens timberland chukka days and ever since has wanted us to accept His gracious act by loving Him and also those around us. When we do this, we will see people in a totally different timberland 14 inch boots light — one that redefines what it means to be ugly or different or weird or strange. http://www.timberland4you.co.uk/ YQ

timberland 14 inch boots | Reply

03.12.2010 12:22:16 #

dd

/post/2009/01/21/http://www.blu-ray-software.net/blu-ray-ripper/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-ripper/ blu ray ripper, /post/2009/01/21/www.blu-ray-software.net/blu-ray-ripper-for-mac/" rel="nofollow">www.blu-ray-software.net/blu-ray-ripper-for-mac/ mac blu ray ripper, /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-creator/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-creator/ blu ray burner, /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-copy/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-copy/ blu ray copy, www.blu-ray-software.net/blu-ray-video-converter/ blu ray converter and /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-player/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-player/ best blu ray player offer the best solution for blu-ray videos
Duplicate /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-ripper/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-ripper/ blu ray dvd with /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-copy/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-copy/ blu ray dvd copy, /post/2009/01/21/www.blu-ray-software.net/blu-ray-ripper-for-mac/" rel="nofollow">www.blu-ray-software.net/blu-ray-ripper-for-mac/ blu ray ripper mac for Mac OS and /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-creator/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-creator/ blue ray burner are good /post/2009/01/21/http://www.blu-ray-software.net/blu-ray-player/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-player/ blu ray player software

dd | Reply

15.12.2010 6:29:11 #

juicy couture handbags

nice post!!!

juicy couture handbags | Reply

Добавить комментарий




biuquote
  • Комментарий
  • Предпросмотр
Loading



Спасибо BlogEngine.NET за основу блога.

Комментарии

Comment RSS