扩展类的依赖注入? [英] Dependency injection for extension classes?

查看:159
本文介绍了扩展类的依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Microsoft Unity用作IoC容器.我有许多扩展类,这些扩展类为我的业务对象添加了有用的方法 这是我今天使用的那种代码:

I'm using Microsoft Unity as my IoC container. I have a number of extension classes which adds useful methods to my business objects This is the sort of code I use today:

public static class BusinessObjectExtensions
{
    public static bool CanDoStuff(this BusinessObject obj) 
    {
        var repository = BusinessHost.Resolver.Resolve<IRepository>();
        var args = new EArgument { Name = obj.Name };
        return repository.AMethod(obj.UserName, args);
    }
}

是否有更好的方法来管理扩展类的依赖项注入?

Is there a better way to manage dependency injection for extension classes?

推荐答案

您实际上应该避免使用扩展方法,除非它们仅适用于内部数据(类本身的属性)或方法中提供的简单数据类型.您不应该在扩展方法中谈论其他依赖项.如果遵循此规则,则根本不需要在IoC中注入扩展类.

You should actually try to avoid extensionmethods unless they only work on internal data (properties in the class itself), or simple datatypes provided in the method. You should not talk to other dependencies in your extension methods. If you follow this rule, you should not need to inject extension-classes with your IoC at all.

这篇关于扩展类的依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆