An IoC container is a standard software component that supports and simplifies IoC. It lets
you register a set of components (i.e., abstract types and your currently chosen concrete
implementations), and then handles the business of instantiating them. You can configure
and register components either with an XML file or with C# code (or both).
At runtime, you can call a method similar to container.Resolve(Type type), where
typecould be a particular interfaceor abstracttype or a particular concrete type, and the
container will return an object satisfying that type definition, according to whatever concrete
type is configured. It sounds trivial, but a good IoC container adds three extra clever features:
Dependency chain resolution: If you request a component that itself has dependencies
(e.g., constructor parameters), the container will satisfy those dependencies recursively,
so you can have component A, which depends on B, which depends on C, and so on. In
other words, you can forget about the wiring on your component circuit board—just
think about the components, because wiring happens magically.
Object lifetime management: If you request component A more than once, should you get
the same actual instance of A each time, or a fresh new instance each time? The container
will usually let you configure the “lifestyle” of a component, allowing you to select from
predefined options including singleton (the same instance each time), transient (a new
instance each time), instance-per-thread, instance-from-a-pool, and so on.
Explicit constructor parameter values configuration: For example, if the constructor for
MembersRepositorydemands a string called connectionString, (as ours did earlier), you can configure a value for it in your XML config file. It’s a crude but simple configuration
system that removes any need for your code to pass around connection strings, SMTP
server addresses, and so on.
So, in the preceding example, you’d configure MembersRepositoryas the active concrete
implementation for IMembersRepository. Then, when some code calls container.Resolves
(typeof(AdminController)), the container will figure out that to satisfy AdminController’
constructor parameters it first needs an object implementing IMembersRepository. It will
get one according to whatever concrete implementation you’ve configured (in this case,
MembersRepository), supplying the connectionStringyou’ve configured. It will then use that to
instantiate and return an AdminController.
阅读(436) | 评论(0) | 转发(0) |