나는 당신이 단 하나 책임 원리 (SRP)와 열리는 닫히는 원리 (OCP)의 2 개의 원리를 위반하고 있다는 것을 주장 할 것입니다.
부트 스트래핑 클래스가 모델 바인딩 또는 자동 매퍼 구성을 변경할 경우 변경해야 할 이유가 하나 이상 있으므로 SRP를 위반합니다.
시스템의 다른 하위 구성 요소를 구성하기위한 추가 부트 스트랩 코드를 추가하려는 경우 OCP를 위반하게됩니다.
내가 보통 어떻게 처리하는지는 다음 인터페이스를 정의한다는 것입니다.
public interface IGlobalConfiguration
{
void Configure();
}
부트 스트랩이 필요한 시스템의 각 구성 요소에 대해 해당 인터페이스를 구현하는 클래스를 생성합니다.
public class AutoMapperGlobalConfiguration : IGlobalConfiguration
{
private readonly IConfiguration configuration;
public AutoMapperGlobalConfiguration(IConfiguration configuration)
{
this.configuration = configuration;
}
public void Configure()
{
// Add AutoMapper configuration here.
}
}
public class ModelBindersGlobalConfiguration : IGlobalConfiguration
{
private readonly ModelBinderDictionary binders;
public ModelBindersGlobalConfiguration(ModelBinderDictionary binders)
{
this.binders = binders;
}
public void Configure()
{
// Add model binding configuration here.
}
}
나는 의존성을 주입하기 위해 Ninject를 사용합니다.IConfiguration
은 AutoMapper
클래스의 기본 구현이며 ModelBinderDictionary
은 ModelBinders.Binder
개체입니다. 그 다음 IGlobalConfiguration
인터페이스를 구현하는 클래스에 대해 지정된 어셈블리를 검사하여 해당 클래스를 복합체에 추가하는 NinjectModule
을 정의합니다.
public class GlobalConfigurationModule : NinjectModule
{
private readonly Assembly assembly;
public GlobalConfigurationModule()
: this(Assembly.GetExecutingAssembly()) { }
public GlobalConfigurationModule(Assembly assembly)
{
this.assembly = assembly;
}
public override void Load()
{
GlobalConfigurationComposite composite =
new GlobalConfigurationComposite();
IEnumerable<Type> types =
assembly.GetExportedTypes().GetTypeOf<IGlobalConfiguration>()
.SkipAnyTypeOf<IComposite<IGlobalConfiguration>>();
foreach (var type in types)
{
IGlobalConfiguration configuration =
(IGlobalConfiguration)Kernel.Get(type);
composite.Add(configuration);
}
Bind<IGlobalConfiguration>().ToConstant(composite);
}
}
다음 코드를 Global.asax 파일에 추가합니다.
public class MvcApplication : HttpApplication
{
public void Application_Start()
{
IKernel kernel = new StandardKernel(
new AutoMapperModule(),
new MvcModule(),
new GlobalConfigurationModule()
);
Kernel.Get<IGlobalConfiguration>().Configure();
}
}
이제 부트 스트래핑 코드가 SRP와 OCP 모두에 적용됩니다. IGlobalConfiguration
인터페이스를 구현하는 클래스를 만들어 부트 스트래핑 코드를 쉽게 추가 할 수 있으며 전역 구성 클래스는 변경해야 할 이유가 하나뿐입니다.
에서 벗어나지 않고 구성을 변경해야합니다. 메서드를 AutoMapperGlobalConfiguration에 추가 할 때마다 – Omu
새 매핑을 추가해야하지만 OCP를 위반하지는 않습니다. OCP는 한번도 다시 만지지 마십시오. OCP는 부트 스트래핑 코드의 소비자 인 GlobalConfigurationModule (GCM)은 구현을 구체화하지 않고 추상화에 의존해야한다고 주장합니다. log4net에 부트 스트래핑을 추가한다면 IGlobalConfiguration을 구현하는 클래스 Log4NetGlobalConfiguration 클래스를 만들 것입니다. 그러나 IGlobalConfiguration 인터페이스의 구체 구현에 대한 복잡한 지식이 없기 때문에 코드의 다른 부분은 수정할 필요가 없으며 GCM은 수정할 필요가 없습니다. – mrydengren
나는 의심 스럽다. Mapper.CreateMap <>()을 실행하면 응용 프로그램이 종료 될 때까지지도가 존재합니까? – JPCF