简体   繁体   English

使用autofac注入类型转换工厂

[英]Injecting a type conversion factory with autofac

I'm trying to get rid of a service locator pattern in an application using Autofac. 我试图摆脱使用Autofac的应用程序中的服务定位器模式。 Currently, I have a class like this: 目前,我有一个这样的课程:

class Factory {
    private readonly ILifetimeScope _scope;
    public Factory(ILifetimeScope scope) {
        _scope = scope;
    }
    public Operation CreateOperation(OperationData dto) {
        var destinationType = NameConventionLookup(dto.GetType().Name);
        return _scope.Resolve(destinationType, new TypedParameter(dto.GetType(), dto));
    }
    private Type NameConventionLookup(Type t) {
        // Return a type by removing parts of the type name and appending others
    }
}

Basically, I get a poco object, and based on this object I create another object with the input as constructor argument. 基本上,我得到一个poco对象,并基于该对象创建另一个对象,并使用输入作为构造函数参数。 Example types: 示例类型:

class MyDto : OperationData {
    public string Foo;
    public int Bar;
}
class MyOperation : Operation {
    public MyOperation(MyDto dto) { ... }
}

Can I get rid of the ILifetimeScope in the factory? 我可以在工厂摆脱ILifetimeScope吗? I would like to instead get some factory method, Func<OperationData, Operation> or the like, but can Autofac generate this? 我想改为使用一些工厂方法,例如Func<OperationData, Operation>之类的方法,但是Autofac可以生成此方法吗? Can I help the library so that it can? 我可以帮助图书馆吗?

只要在合成根目录中定义了您的Factory类,就没有理由删除对ILifetimeScope的引用,因为在这种情况下,不是Service Locator反模式 ,而仅是Mechanics

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM