Autofac:注册显式的通用接口
创始人
2024-11-12 13:00:20
0

以下是一个使用Autofac注册显式通用接口的示例代码:

using System;
using Autofac;

public interface IRepository
{
    void Add(T item);
}

public class Repository : IRepository
{
    public void Add(T item)
    {
        Console.WriteLine($"Adding {item} to the repository");
    }
}

public class MyClass
{
    private readonly IRepository _repository;

    public MyClass(IRepository repository)
    {
        _repository = repository;
    }

    public void DoSomething()
    {
        _repository.Add("Hello World");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        // 注册显式的通用接口
        builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>));

        builder.RegisterType();

        var container = builder.Build();
        var myClass = container.Resolve();

        myClass.DoSomething();
    }
}

在这个示例中,我们定义了一个IRepository接口和一个Repository实现。MyClass依赖于IRepository接口。我们使用builder.RegisterGeneric方法将Repository注册为IRepository的实现。然后,我们使用builder.RegisterType注册MyClass

最后,我们使用container.Resolve方法从容器中解析MyClass实例,并调用DoSomething方法。

当运行这个示例时,输出应该是"Adding Hello World to the repository"。

相关内容

热门资讯

4分钟详情!金州水鱼有挂吗,w... 4分钟详情!金州水鱼有挂吗,wpk德州扑克线上(详细透视辅助工具教程)1、这是跨平台的金州水鱼有挂吗...
3分钟透明!衢州都莱,德扑ai... 1、3分钟透明!衢州都莱,德扑ai机器人软件开发(详细透视辅助挂教程)。2、衢州都莱透视辅助简单,衢...
5分钟总结!小白大作战外挂,微... 5分钟总结!小白大作战外挂,微扑克超级统计(详细透视辅助器教程);亲,其实确实真的有挂(需添加指定薇...
两分钟了解!边锋斗地主有猫腻吗... 两分钟了解!边锋斗地主有猫腻吗,微扑克wpk有挂(详细透视辅助插件教程);实战中需综合运用上述技巧,...
十分钟教学!福建天天开心辅助器... 十分钟教学!福建天天开心辅助器真的,EV扑克辅助软件(详细透视辅助app教程);小薇(透视辅助)致您...
7分钟教程!钱塘十三水有吗,w... WePoker透视辅助版本稳定性对比与推荐‌:7分钟教程!钱塘十三水有吗,wepoke软件透明挂辅助...
5分钟方法!yy比鸡挂是真的吗... 5分钟方法!yy比鸡挂是真的吗,poker辅助工具(详细透视辅助软件教程)这是由厦门游乐互动科技有限...
九分钟透明!369山东麻将插件... 九分钟透明!369山东麻将插件,微扑克模拟器是有(详细透视辅助工具教程);原来确实真的有挂(需添加指...
3分钟了解!南通长牌怎么开挂,... 3分钟了解!南通长牌怎么开挂,微扑克wpk有挂(详细透视辅助工具教程);免费南通长牌怎么开挂平台AI...
9分钟技巧!财神十三张,wpk... 9分钟技巧!财神十三张,wpk辅助(详细透视辅助挂教程);原来确实真的有挂(需添加指定薇757446...