[英]In Castle Windsor, can I register a Interface component and get a proxy of the implementation?
[英]Can i inject component without interface use windsor
我喜欢ioc。 之前,我在Java中使用Spring,现在,我想在C#中使用DI。 我找到了Castle.windsor。 但这似乎并不是直接注射类。
现在,我尝试此方法,但是失败了……。有人,您可以帮我解决这个问题吗? 或者,告诉我,我可以使用什么DI框架?
Program.cs
using System;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
namespace InjectionConsole
{
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Install(new MainInstaller());
var service1 = container.Resolve<Service1>();
service1.Say();
// clean up, application exits
container.Dispose();
Console.ReadKey();
}
}
class MainInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Classes.FromThisAssembly());
}
}
}
Service1.cs
using System;
namespace InjectionConsole
{
class Service1
{
private Service2 Service2 { get; set; }
public void Say()
{
Console.WriteLine("Hello, I m Service 1, let me call Service 2");
Service2.Say();
}
}
}
Service2.cs
using System;
namespace InjectionConsole
{
class Service2
{
public void Say()
{
Console.WriteLine("Hello, I m Service 2");
}
}
}
我假设您要解析Service1实例中的Service2。 您可以通过构造函数注入来实现
using System;
namespace InjectionConsole
{
class Service1
{
public Service1(Service2 s2) {
this.Service2 = s2;
}
private Service2 Service2 { get; set; }
public void Say()
{
Console.WriteLine("Hello, I m Service 1, let me call Service 2");
Service2.Say();
}
}
}
似乎您没有将Service1
和Service2
类标记为public
,这将使它们默认为内部。 Classes.FromThisAssembly()
方法仅加载公共类型,除非您明确告诉它也加载非公共类型(不建议这样做!)。 检查该文档的温莎城堡GitHub的文档页面上。
我的答案与另一个类似,但有一个区别:
public class Service1
{
private readonly Service2 _service2;
public Service1(Service2 service2) {
_service2 = service2;
}
public void Say()
{
Console.WriteLine("Hello, I m Service 1, let me call Service 2");
_service2.Say();
}
}
首先,无论您是否使用像Windsor这样的容器,都将以完全相同的方式编写类本身。 该类必须从某处“获取”其依赖项( Service2
的实例)。 因此,我们将其放入构造函数中。 Service1
期望创建它的任何Service2
提供Service2
。 由于您使用的是容器,因此容器会创建Service1
,它会在构造函数中看到它需要Service2
,并提供它。
将_service2
为readonly
字段强调指出,一旦创建_service2
(构造函数完成执行), Service1
就无法进一步控制_service2
的值。 它已设置且无法更改,即使在Service1
也无法更改。 这很重要,因为我们不希望Service1
控制该依赖性。 我们希望它需要这种依赖性。 它只接受传入的任何值并使用它。
再次,那是分裂头发的区别。 如果您不将_service2
readonly
,则可能无论如何也不会对其进行更改。 但这清楚表明您无法更改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.