.net-core 依赖注入 [英] .net-core Dependency Injection

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

问题描述

我有一个通用存储库,我想为 DI 注册它,它实现了一个接口 IRepository.

I have a Generic repository which I want to register for DI, it implements an interface IRepository.

通常我会像这样创建一个实例:

Normally I would create an instance of it like this:

IRepository repo = new Repository<Order>();

但是,我正在尝试在发布之前加快 .net 5 的速度,并希望将其与 DI 一起使用,我采取了以下措施:

However I am trying to get up to speed in .net 5 ahead of release and want to get this working with DI, I have resorted to the following :

services.AddTransient<DAL.IRepository<Models.Order>, DAL.Repository<Models.Order>>();

但这感觉不对,我不希望模型中的每个类都有 50 多行...

But this feels wrong, I don't want 50+ lines in there one for each of the classes in my model...

我在网上找不到任何关于此的信息,我知道它可能与其他 ioc 容器一起使用.>

I cannot find anything online about this, I know its possible with other ioc containers.. but as this is a learning project I dont want to use another container, Im aiming to do it all with .net5s native container.

推荐答案

在对其他答案的评论中进行了一些来回转发后,我有了一个可行的解决方案,这可能不是最好的方法,但它有效.如果我找到更好的方法来实现这一点,我会再次更新.

After some back and forwards in the comments to other answers I have a working solution, It might not be the best way but it works. Ill update again if I find a better way to implement this.

我遇到的两个问题是:需要注册一个泛型接口,这里的问题是我注意力不集中..我注册泛型类型的语法错误,当然是:

The two issues I had were : Needed to register a generic interface, the issue here was a lapse in concentration on my part.. I had the syntax wrong for registering a generic type which of course is :

services.AddTransient(typeof(IRepository<>), typeof(Repository<>));

第二个问题是我有一个程序集,其中包含 50 多个我想要注册的不同模型,我解决这个问题的方法是编写一个方法,我可以将程序集列表和我想要的命名空间一起传递给它进行注册,它会遍历符合条件的任何类型并将它们注册到 DI 容器中.

The second issue was that I have an assembly which contains 50+ different models which I wanted registered, The way that I addressed this was to write a method that I can pass a list of assemblies to along with the Namespace that I want to register and it iterates over any types that match the criteria and registers them in the DI container.

public void RegisterModels(IServiceCollection services, string[] Assemblies, string @NameSpace)
    {
        foreach (var a in Assemblies)
        {
            Assembly loadedAss = Assembly.Load(a);

            var q = from t in loadedAss.GetTypes()
                    where t.IsClass && !t.Name.Contains("<") && t.Namespace.EndsWith(@NameSpace)
                    select t;

            foreach (var t in q.ToList())
            {
                Type.GetType(t.Name);
                services.AddTransient(Type.GetType(t.FullName), Type.GetType(t.FullName));
            }
        }
    }

然后从 startup.cs 方法 ConfigureServices 调用它:

This is then called from the startup.cs method ConfigureServices :

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<TestContext>(options =>
                options.UseSqlServer(@"Server=LOCALHOSTSQLEXPRESS;Database=Test;Trusted_Connection=True;"));

        services.AddMvc();

        RegisterModels(services, new string[] { "UI" }, "UI.Models");

        services.AddTransient(typeof(IRepository<>), typeof(Repository<>));
    }

可能有更好的方法来做到这一点,肯定会使用不同的 DI 容器,如果有人有改进,请告诉我.

There may be a better way to do this, there definitely is using different DI containers, if anyone has improvements to offer please let me know.

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

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