공장 메서드가있는 클래스가 있는데, 직렬화 된 버전을 찾으면 반환해야합니다. 그렇지 않으면 자신의 새 인스턴스를 반환해야합니다.
class ClassToDeserialize : List<SomeClass>
{
public static event Func<ClassToDeserialize> onNoDeserializationFile;
public ClassToDeserialize(SomeClass firstInList)
{
this.Add(firstInList);
}
public static ClassToDeserialize DeserializeIfAny(string jsonPath)
{
if (File.Exists(jsonPath))
return JsonConvert.DeserializeObject<ClassToDeserialize>(File.ReadAllText(jsonPath));
return onNoDeserializationFile();
}
}
DI를 사용하도록 응용 프로그램을 리팩터링하려고하는데 문제는 ClassToDeserialize에 대해 이중 바인딩을 수행해야한다는 것입니다.
static void Main(string[] args)
{
string json = @"C:\obj_serialized.txt";
IKernel ninjectKernel = new StandardKernel();
ClassToDeserialize.onNoDeserializationFile += (() => ninjectKernel.Get<ClassToDeserialize>("NoSerialization"));
ninjectKernel.Bind<ClassToDeserialize>().ToSelf().Named("NoSerialization").WithConstructorArgument("jsonPath", json);
ninjectKernel.Bind<ClassToDeserialize>().ToConstant<ClassToDeserialize>(ClassToDeserialize.DeserializeIfAny(json));
}
I added the onNoDeserializationFile event to let ninject handle all instantiations and decouple my business logic from my IoC, and then I intend to Get a Service which has a dependency upon ClassToDeserialize, and to be able to resolve this request I need to find a way to tell ninject that when a serialization file is found it should call the corresponding binding (even though the context is the same).
ninjectKernel.Get<DependantClass>().DoSomething();
I'm aware this resembles the Service-Locator Antipattern, but is not the only way I'm using the container and this behavior is tied only to the entry point of my application.
What's the proper way for solving this?
You could put that decision logic into an IProvider
.
Alternatively there's the When
binding syntax for conditions. See Contextual Bindings.
사용 방법 :
kernel.Bind<ClassToDeserialize>().ToSelf()
.WithConstructorArgument(...); // default binding
kernel.Bind<ClassToDeserialize>()
.ToMethod(ctx => JsonConvert.DeserializeObject<ClassToDeserialize>(...))
.InSingletonScope()
.When(ctx => File.Exists(...));
(힌트 : 컴파일하지 않았으므로 메서드 시퀀스가 약간 벗어 났을 수 있습니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다