コンテナ(非常にスマートな工場)とアドバイス(すべての面倒な詳細を処理する)について考えるかもしれません。インターセプタクラスを考え出す
//a class that knows how to take care of the messy infrastructure details
public class MyMessyInterceptor : IInterceptor {
public void Intercept(IInvocation invocation) {
//handle the messy details of continuing with the method-invocation,
//but within a try-catch-finally that includes exception handling and
//call logging.
}
}
//a function that will configure a container (very smart factory)
public IContainer CreateContainer() {
var builder = new ContainerBuilder();
//tell the container-builder about the interceptor
builder
.Register(c => new MyMessyInterceptor())
.Named("keep-my-code-clean")
;
//tell the container what to do when you ask it for a ISomething
builder
.Register<SomethingImpl>()
.As<ISomething>()
.InterceptedBy("keep-my-code-clean")
;
return builder.BuildContainer();
}
//some function out there in your code somewhere that needs to make a
//service call; there's hundreds of functions out there just like this
//in your code, and they all just got much simpler
public object GottaGoDoSomething() {
//find the container
var container = GetTheSingletonContainerObject();
//ask for an instance of ISomething - it knows to provide a
//SomethingImpl wrapped in an interceptor that takes care of all
//the logging and exception handling
var something = container.resolve<ISomething>();
//call the big method
return something.DoSomething();
//magically (not really), the exception handling and logging are
//already taken care of
}
は一度だけ行われます
Dear Mr. Container Sir,
Whenever I request from you an instance object of the interface ISomething,
please construct for me an instance of the concrete class SomethingImpl;
in addition, please see to it (however you do it) that, whenever I call a
method on this instance, it is wrapped within a complicated and messy try-
catch-finally which logs exceptions and mark calls as completed. That way,
all I have to do is write the business logic that goes into the SomethingImpl
and I don't have to worry about all the messy infrastuctural details.
Sincerely,
Mr. Agile.
はあなたに、コード内で、これを見るかもしれません。各インターセプタとサービスクラスの登録は、一度だけ発生します。コンテナの設定(非常にスマートな工場)は確かに複雑です。
しかし、サービスオブジェクトを使用する必要があり、例外処理やロギングなどの複雑で面倒なインフラストラクチャの詳細内にそのコードを埋め込む必要がある場所はすべて、非常にきれいで、非常に単純です。 CreateContainer
は1つしかありませんが、何百ものGottaGoDoSomething
がありますので、少し複雑ですが簡単です。
(注:このコード例では、AutofacコンテナフレームワークとCastleインターセプタフレームワークを使用しています。これは依存関係注入パターンではなくサービスロケーションパターンの例ですが、インターセプタ依存性注入を説明しないように容器に登録してください)。
Spring.Netあなたは既に理想的な形式を持ってしてみてください。 –