0

How to call a method inside another assembly that you cannot reference?

I'm trying to made a call represented by the red line, but, my domain layer cannot reference my application layer because it will cause a cyclic redundancy, so, looking on internet I found a way to do that loading the assembly, but, I'm not sure if it is the better way to do that

The application use dependency-injection, this is a simplified diagram of the application:

Diagram

This is the complete implementation of the Domain class

public class SomeDomainService<T> : ISomeDomainService<T>
    {
        private readonly IServiceProvider _serviceProvider;

        public SomeDomainService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task<SomeEntity> SomeProcess(SomeEntity someEntity)
        {
            await Task.Delay(1000);

            someEntity.Id = new Random().Next(3000);
            someEntity.Name = $"Entity {someEntity.Id}";
            someEntity.Description = "lorem ipsum";
            /*
             * 
             * SOME PROCESS
             * 
            */

            var aplicationAssembly = Assembly.Load("Application");
            var types = aplicationAssembly.GetTypes();
            var type = types.FirstOrDefault(t=> t.Name == "IAnotherApplicationService`1");

            if (type != null)
            {
                var domainMessage = new Message {
                    Id = someEntity.Id.ToString(),
                    Title = $"Some entity {someEntity.Name}",
                    Body = "Message from Domain"
                };


                var runtimeType = type.MakeGenericType(typeof(Message));
                var methods = runtimeType.GetRuntimeMethods();

                var service = _serviceProvider.GetService(runtimeType);

                var method = service.GetType().GetMethod("SendSomeMessage");

                method.Invoke(service, new object[] { domainMessage});
            }

            return someEntity;
        }
    }
1
  • 2
    The general answer to your question (about untangling dependencies) is to use an interface (or interfaces) in another assembly. You implement the interface(s) in one of your assemblies, and you refer to instances of the types you are interested not by the raw type, but by the interfaces
    – Flydog57
    May 20 at 1:49

1 Answer 1

0

Typically when you end with a circular dependency you should consider to refactor your code because something is not placed in the right place. If the domain service needs to call the application service, consider to move that functionality from the application to the domain layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.