城堡温莎属性注射

时间:2011-10-25 11:47:00

标签: dependency-injection castle-windsor

我是一个温莎诺布,我有一些问题让依赖注入工作。即时通讯使用asp.net Web应用程序。

我做了以下

public interface IHandler{
    ...
}

public class Handler : IHandler{
    ...
}

然后我尝试在global.asax application_start

中注册代码
container.Register(Component
    .For(typeof(IHandler))
    .ImplementedBy(typeof(Handler))
    .Named("handler"));

当我想使用Handler时,我创建了一个属性

public IHandler handler{get;set;}

但是当我尝试使用它时,它是空的?为什么?我错过了吗?

祝你好运

更新

我唯一注册/解决的是以下内容:

container.Register(Component
    .For(typeof(IHandler))
    .ImplementedBy(typeof(Handler))
    .Named("handler"));

container.Resolve<IHandler>();

我是否需要做其他事情,是否可以运行此att应用程序启动?

更新2

这个问题可以解决,因为我试图依赖注入ascx控件吗?

3 个答案:

答案 0 :(得分:4)

  1. 确保具有IHandler属性的组件也在Windsor中注册(和解析)。

  2. 您说这是一个ASP.NET应用程序。 Windsor组件的默认生活方式是单身。您确定要将此组件共享吗?您可能需要此组件的瞬态或每网络请求生活方式。

答案 1 :(得分:1)

尝试从注册中删除名称,如下所示:

container.Register(Component
    .For(typeof(IHandler))
    .ImplementedBy(typeof(Handler)));

或者,如果必须为组件命名,则可以将ServiceOverrides用于使用类:

container.Register(Component
    .For<SomeConsuer>()
    .ServiceOverrides(new { handler = "handler" }));

答案 2 :(得分:1)

如果您要注册多个接口/服务,那么我建议按惯例注册(这在文档中推荐)。考虑一下:

container.Register(
            AllTypes.FromAssemblyNamed("Assembly")
                .Where(Component.IsInNamespace("Assembly.Namespace"))
                .WithService.DefaultInterface()
                .Configure(c => c.LifeStyle.Transient));

此方法根据类型名称和接口名称执行匹配。更多信息Registering Components By Convention

相关问题