加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 我可以在Orchard CMS中使用我的Ninject .NET项目吗?

发布时间:2020-12-16 03:27:51 所属栏目:asp.Net 来源:网络整理
导读:我正在使用Orchard CMS创建一个网站,我有一个用Ninject编写的外部.NET项目用于依赖注入,我想与Orchard CMS中的模块一起使用.我知道Orchard使用Autofac进行依赖注入,这引起了我的问题,因为我之前从未使用过DI. 我创建了一个Autofac模块UserModule,它注册了一
我正在使用Orchard CMS创建一个网站,我有一个用Ninject编写的外部.NET项目用于依赖注入,我想与Orchard CMS中的模块一起使用.我知道Orchard使用Autofac进行依赖注入,这引起了我的问题,因为我之前从未使用过DI.

我创建了一个Autofac模块UserModule,它注册了一个源UserRegistrationSource,如下所示:

UserModule.cs

public class UserModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterSource(new UserRegistrationSource());
    }
}

UserRegistrationSource.cs

public class UserRegistrationSource : IRegistrationSource
{
    public bool IsAdapterForIndividualComponents
    {
        get { return false; }
    }

    public IEnumerable<IComponentRegistration> RegistrationsFor(Service service,Func<Service,IEnumerable<IComponentRegistration>> registrationAccessor)
    {
        var serviceWithType = service as IServiceWithType;
        if (serviceWithType == null)
            yield break;

        var serviceType = serviceWithType.ServiceType;
        if (!serviceType.IsInterface || !typeof(IUserServices).IsAssignableFrom(serviceType) || serviceType != typeof(IUserServices))
            yield break;

        var registrationBuilder = // something...

        yield return registrationBuilder.CreateRegistration();
    }
}

UserServices.cs

public interface IUserServices : IDependency
{
    void Add(string email,string password);
}

public class UserServices : IUserServices
{
    private readonly EFMembershipManager _manager;

    public UserServices(EFMembershipManager manager)
    {
        _manager = manager;
    }

    public void Add(string email,string password)
    {
        _manager.createUser(email,password);
    }
}

EFMembershipManager.cs构造函数

public EFMembershipManager(ServerRepository db,ServerRepositoryMembershipProvider membershipProvider,string testUsername,string serverUsername)
{
...
}

EFMembershipManager是来自外部项目的类,它使用Ninject作为DI,并使用ServerRepository和ServerRepositoryMembershipProvider,它们也使用Ninject注入.

而现在我被卡住了……

UserRegistrationSource应该将Ninject容器(内核)作为构造函数参数,并尝试查找IUserServices服务,然后将解析调解到Ninject内核并返回一个空的Enumerable,以便Autofac不会尝试解析与IUserServices相关的任何内容,或者这是错误的做法?

解决方法

Autofac支持 registration sources(以及更多注册来源 here).注册源是容器在尝试解析类型时将参考的服务.源可以通过构建类型的方式响应,也可以响应指示源无法提供所请求类型的空列表.

在您的情况下,可以实现注册源,尝试从Ninject容器中解析所请求的类型.

我对Orchard不太熟悉,但我猜它使用配置文件来配置Autofac.我的建议是你创建a simple Autofac module来注册你的注册源实现,并将你的Orchard配置为load the module from config.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读