- Posted by 꽃미남 on 2009. 04. 10 16:46
안녕하세요. 꽃미남 입니다.
지난번 Spring.Net을 이용한 DI 활용 - Part 1 에 이어 Part 2 를 진행하여 보겠습니다.
Part 1에서는 DI에 대한 개념적인 내용들을 소개해 드렸습니다.
이번 글은 Spring.Net을 이용한 DI의 사용에 대해 알아보겠습니다.
예제 소스 : springnet_di.zip (10.19 kb)
Spring.Net 설정
Spring.Net의 IoC 컨테이너는 Spring.Core.dll에 있으므로 이를 참조하여야 합니다.
(C:\Program Files\Spring.NET 1.2.0\bin\net\2.0\release)
여기에 spring.net의 설정을 입력 할 구성 파일(App.Config)를 추가하고 spring.net의 설정을 추가합니다.
(IoC 컨터이너를 주로 설정 파일을 통하여 설정 된 내용을 가지고 사용합니다.)
참고로 C:\Program Files\Spring.NET 1.2.0\doc\schema 에 있는 스키마(xsd)를 VS의 스키마에 넣어주면 인텔리센스가 작동합니다.
(VS 2008의 기본 경로는 C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas 입니다.)
혹은 NAnt를 사용하시면 자동으로 설치됩니다.
(nant -f:"C:\Program Files\Spring.NET 1.2.0\doc\schema\install-schema.build")
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<description>Mvpmagazine DI Sample</description>
</objects>
</spring>
</configuration>
ContextHandler : IConfigurationSectionHandler 로부터 상속받았으며 custom section의(spring/context) 설정을 등록한다.
DefaultSectionHandler : 역시 IConfigurationSectionHandler로부터 상속 받았으며 object에 대한 정의를 등록한다.
이번 예제에서는 resource를 App.config의 설정(config://spring/objects)를 사용하였지만 <resource uri="file://MessageService.xml" />와 같이 xml 설정 파일을 따로 뺄수도 있습니다.
간단한 설정은 App.Config를 사용하겟지만 설정이 많아지면 많아질수로 App.Config에 모두 관리하기는 힘드므로 xml로 분리하여 관리하여야 합니다.
Spring.Net의 사용
Spring.Net의 간단한 사용을 위하여 SMS.cs 라는 클래스를 하나 추가 한 후, 이 SMS를 등록하여 사용하도록 하겠습니다.
SMS.cs는 MessageService 라는 새 클래스 라이브러리 프로젝트를 추가 한 후 등록하도록 하겠습니다.
SMS.cs는 다음과 같은 간단한 클래스 입니다.
public class SMS
{
public SMS() { }
public void SendMessage(string msg)
{
Console.WriteLine("{0} : {1}", "SMS", msg);
}
}
SMS의 사용을 위하여 App.config에 SMS Object를 등록합니다.
자.. 이제 준비는 끝났습니다.
사용만 하면 됩니다.
(쉽죠~~~??? =_=;;;)
먼저 MessageService 프로젝트를 참조에 넣어주시고 다음과 같이 코딩을 한 후 실행합니다.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using MessageService;
namespace springnet_di
{
class Program
{
static void Main(string[] args)
{
using (IApplicationContext ctx = ContextRegistry.GetContext())
{
SMS sms = (SMS)ctx.GetObject("SMS");
sms.SendMessage("꽃미남에게 문자주세요.");
}
}
}
}
IApplicationContext는 객체의 생성과 소멸을 담당하는 IObjectFactory 인터페이스를 상속한 인터페이스로 object factory의 모든 기능을 가지고 있습니다.
(IObjectFactory는 IoC 컨테이너의 접근, 관리에 대한 핵심 인터페이스 입니다.)
IApplicationContext 보다 IObjectFactory가 가볍지만 IApplicationContext이 쓰임새가 보다 넓으므로 민감한 환경이 아니라면 IApplicationContext 가 일반적으로 추천됩니다.
SMS sms = (SMS)ctx.GetObject("SMS");
설정 파일에 등록 된 SMS객체를 사용하는 항목입니다.
Spring.Net의 객체들은 기본적으로 singleton 으로 생성되며 singleton을 원하지 않을시에는 singletone="false"를 명시적으로 표시해줘야 합니다.
Setter Injection
DI의 한 방식인 Setter Injection은 Setter 메소드를 이용하여 대상 객체를 주입하는 방식입니다.
속성(Property)의 Setter를 이용합니다.
물론 자동할당은 아니며 설정을 통하여 주입이 일어납니다.
이 예제를 설명을 위하여 메시지를 보내는 MessageSender 클래스, IMessageService 인터페이스, MAIL 클래스를 추가 한 후, SMS, MAIL 클래스는 IMessageService 인터페이스 에서 상속받는 것으로 변경하겠습니다.
IMessageService.cs
public interface IMessageService
{
void SendMessage(string msg);
}
SMS.cs
public class SMS : IMessageService
{
public SMS() { }
public void SendMessage(string msg)
{
Console.WriteLine("{0} : {1}", "SMS", msg);
}
}
Mail.cs
public class Mail : IMessageService
{
public Mail() { }
public void SendMessage(string msg)
{
Console.WriteLine("{0} : {1}", "Mail", msg);
}
}
MessageSender.cs
public class MessageSender
{
private IMessageService _messageService;
public IMessageService MessageServie
{
get { return _messageService; }
set { _messageService = value; }
}
public MessageSender() { }
public void SendMessage(string msg)
{
_messageService.SendMessage(msg);
}
}
App.Config
<objects xmlns="http://www.springframework.net">
<description>Mvpmagazine DI Sample</description>
<object name="SMS" type="MessageService.SMS, MessageService" singleton="true"></object>
<object name="Mail" type="MessageService.Mail, MessageService" singleton="true"></object>
<object name="MessageSender" type="MessageService.MessageSender, MessageService" singleton="false">
<property name="MessageServie" ref="Mail"></property>
</object>
</objects>
MessageSernder 이름으로 object를 추가하고 MessageService 속성에 Mail 객체를 할당합니다.
이를 다음과 같이 사용하면 말끔히 실행됩니다.
using (IApplicationContext ctx = ContextRegistry.GetContext())
{
MessageSender messageSender = (MessageSender)ctx.GetObject("MessageSender");
messageSender.SendMessage("꽃미남에게 문자주세요");
}
Constructor Injection
역시 DI의 한 방식이며, 생성자를 통하여 대상 객체를 주입하는 방식입니다.
MessageSernder 클래스와 App.Config를 다음과 같이 변경합니다.
MessageSernder.cs
public class MessageSender
{
private IMessageService _messageService;
public MessageSender(IMessageService messageService)
{
_messageService = messageService;
}
public void SendMessage(string msg)
{
_messageService.SendMessage(msg);
}
}
App.Config
<objects xmlns="http://www.springframework.net">
<description>Mvpmagazine DI Sample</description>
<object name="SMS" type="MessageService.SMS, MessageService" singleton="true"></object>
<object name="Mail" type="MessageService.Mail, MessageService" singleton="true"></object>
<object name="MessageSender" type="MessageService.MessageSender, MessageService" singleton="false">
<constructor-arg name="messageService" ref="Mail"></constructor-arg>
</object>
</objects>
MessageSender 클래스는 생성자로 IMessagService 인터페이스의 인자를 받아 _messageService로 할당하는 것으로 변경되었습니다.
App.Config에서는 MessageSender가 속성 대신 생성자의 인자(constructor-arg)로 messageService 에 Mail 객체를 할당하게끔 역시 변경되었습니다.
오호라.. 역시나 실행이 잘 됩니다. ^ ^
이상으로 Spring.Net의 DI 사용법을 간단히 살펴봤는데요, 벌써 Spring.Net에 혹~ 하실거 같지 않으신가요?
이처럼 DI는 사용이 쉽고 효율적이라 Spring.Net에 반하게 앞잡이(?) 역할을 톡톡히 하리라 생각됩니다.
다음 포스트에서는 DI의 몇가지 설정, 사용 방법에 대해 간략이 기술 한 후 부족하지만 Spring.Net의 DI 사용에 대해 내용을 마칠까 합니다.
그럼.. 모든 분들 좋은 주말 보내세요~~ ^ ^
평점 5.0 / 1회 참여
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5