Autofac-如何注册课程连接到<> [英] Autofac - How to register a class<,> to interface<>

查看:57
本文介绍了Autofac-如何注册课程连接到<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试注册我的存储库类,该类需要两个通用参数到存储库接口(一个参数通用).

I'm trying to register my repository class which is take two generic parameter to repository interface (one parameter generic).

public class RepositoryBase<T, O> : IDataAccess<T>

public interface IDataAccess<T>

推荐答案

仅在接口中提供一个通用参数时,Autofac不知道如何设置RepositoryBase的第二个通用参数.因此,除非您对 object dynamic 或某些基类感到满意,否则需要以某种方式指定第二个参数以实例化服务.为了实现这一目标,您可以创建一个像这样的工厂:

Autofac don't know how to set the second generic parameter of RepositoryBase when you only want to provide one generic argument in the interface. So you need to somehow specify the second argument in order to instantiate the service unless you are happy with object, dynamic or some base class. In order to achieve this you can create a factory like this:

public class BaseRepositoryFactory<T1> : IDataAccessFactory<T1>
{
    private readonly IComponentContext context;

    public BaseRepositoryFactory(IComponentContext context)
    {
        this.context = context;
    }

    public IDataAccess<T1> Create<T2>()
    {
        return context.Resolve<IRepositoryBase<T1, T2>>();
    }
}

public interface IDataAccessFactory<T1>
{
    IDataAccess<T1> Create<T>();
}

public interface IRepositoryBase<T1, T2> : IDataAccess<T1>
{
}

public class RepositoryBase<T1, T2> : IDataAccess<T1>, IRepositoryBase<T1, T2>
{
}

然后注册以下服务:

builder.RegisterGeneric(typeof(BaseRepositoryFactory<>))
    .As(typeof(IDataAccessFactory<>));
builder.RegisterGeneric(typeof(RepositoryBase<,>))
    .As(typeof(IRepositoryBase<,>));

之后,您可以解决工厂并创建服务;

After that you can resolve the factory and create service;

var factory = c.Resolve<IDataAccessFactory<string>>();
IDataAccess<string> serviceInterface = factory.Create<int>(); 
var serviceConcrete = (RepositoryBase<string, int>)factory.Create<int>();

这样,您可以将第二个参数的声明移至工厂方法.这样做的缺点是您需要为每种类型创建此类工厂.为了避免这种情况,您可以定义带有两个通用修饰符IDataAccess<T1, T2>的附加接口,并在具体的类中实现它并注册它,以便您的工厂看起来像这样,并且可以用于任何类型:

So this way you can move the declaration of a second argument to a factory method. The drawback of this is that you need to create such factories for each type. To avoid this you can define additional interface with two generic arugments IDataAccess<T1, T2> and implement it in concrete class and register it so your factory can look like this and will work for any type:

public class DataAccessFactory<T1> : IDataAccessFactory<T1>
{
    private readonly IComponentContext context;

    public DataAccessFactory(IComponentContext context)
    {
        this.context = context;
    }

    public IDataAccess<T1> Create<T2>()
    {
        return context.Resolve<IDataAccess<T1, T2>>();
    }
}

这篇关于Autofac-如何注册课程连接到&lt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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