위키에서 Autofac 문서가 도움이된다는 사실을 발견했지만, XML 설정과 모듈에 관한 부분은 다소 불분명합니다. 이제는 샘플을 사용해 보았지만 (아래에서 설명 함) Autofac 컨텍스트 내에서 구성에 대한 일종의 저속한 접근 방식인지 여부는 확실하지 않습니다. 특히 설정 파일과 코드 파일에 실제로 필요한 것이 더 많거나 적은지 잘 모르겠습니다.autofac에서 모듈과 설정 파일 사용하기
여기에 코드입니다 :
using System;
using System.IO;
using Autofac;
using Autofac.Configuration;
namespace AutofacTest.Animals
{
interface IAnimal
{
void Speak ();
}
abstract class Animal : IAnimal
{
protected TextWriter Writer
{
get;
private set;
}
protected Animal (TextWriter writer)
{
this.Writer = writer;
}
public abstract void Speak ();
}
class Dog : Animal
{
public Dog (TextWriter writer)
: base (writer)
{
}
public override void Speak ()
{
this.Writer.WriteLine ("Arf!");
}
}
class Cat : Animal
{
public Cat (TextWriter writer)
: base (writer)
{
}
public override void Speak ()
{
this.Writer.WriteLine ("Meow");
}
}
// In actual practice, this would be in a separate assembly, right?
class AnimalModule : Module
{
protected override void Load (ContainerBuilder builder)
{
builder.RegisterInstance (Console.Out).As<TextWriter> ().SingleInstance ();
builder.Register (d => new Dog (d.Resolve<TextWriter> ())).As<IAnimal> ();
}
}
class Program
{
static void Main ()
{
Console.ForegroundColor = ConsoleColor.Yellow;
ContainerBuilder builder = new ContainerBuilder ();
ConfigurationSettingsReader reader = new ConfigurationSettingsReader();
builder.RegisterModule (reader);
//builder.RegisterModule (new AnimalModule ());
builder.Build ().Resolve<IAnimal> ().Speak ();
Console.ReadKey ();
}
}
}
그리고 여기에 관련된 설정 파일입니다 : 모두가 잘 작동
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
</configSections>
<autofac defaultAssembly="AutofacTest">
<components>
<component
type="AutofacTest.Animals.Cat"
service="AutofacTest.Animals.IAnimal" />
<component type="System.IO.StreamWriter" service="System.IO.TextWriter">
<parameters>
<parameter name="path" value="C:\AutofacTest.txt"/>
<parameter name="append" value="false" />
</parameters>
<properties>
<property name="AutoFlush" value="true" />
</properties>
</component>
</components>
<modules>
<module type="AutofacTest.Animals.AnimalModule, AutofacTest"/>
</modules>
</autofac>
</configuration>
이. 응용 프로그램에서 "Meow"를 텍스트 파일로 출력합니다. 구성 요소를 주석 처리하면 응용 프로그램이 "Arf!"를 출력합니다. 콘솔에.
그럼 모든 것이 여기에 있습니까? 아니면 이것에 대해 더 좋은 방법이 있습니까?
그리고 모듈 기반 구성 뒤에 사고에 대해 조금 확실 해요 :
내가, 실제 상황에서, 모듈은 응용 프로그램의 나머지 부분에서 별도의 어셈블리에 있어야한다는 수정 있습니까?
모듈의 주요 기능 중 하나가 DI 컨테이너의 기본 구성 설정 집합을 제공한다는 점을 올바르게 알고 있습니까?
이상적으로, 설정 파일은 얼마나 확장되어야합니까? 즉, Autofac을 사용할 때 내가 감시해야 할 설정 파일 방지 패턴은 무엇입니까?
미리 답변 해 주셔서 감사합니다.
musicologyman
단지 알림 -이 더 이상 * * 유효하지 않습니다 AutoFac 4.0을. 구성 사용 방법은 버전 4.0 설명서를 참조하십시오. – codeputer