开发者

is it ok to use StructureMap like this? asp.net MVC 3

开发者 https://www.devze.com 2023-04-09 21:56 出处:网络
i have a doubt that i am not using the best practice for using Structure-Map. all working fine but just a confusion in mind.

i have a doubt that i am not using the best practice for using Structure-Map.

all working fine but just a confusion in mind.

my code look like this.

global.asax

  IContainer container = new Container(
            x => { 

                    x.For<IUserRepo>().Use<UserRepo>();
                    x.For<IPostRepo>().Use<PostRepo>(); // this is the soultion for the error
            });
        DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));

PostController

private readonly IPostRepo _postRepo;

    public PostController(IPostRepo postRepo)
    {
        this._postRepo = postRepo;
    }

StructureMapDependencyResolver

public class StructureMapDependencyResolver : IDependencyResolver
    {
        private readonly IContainer _container;
        public StructureMapDependencyResolver(IContainer container )
        {
            this._container = container;
        }

        public object GetService(Type serviceType)
        {
            object instance = _container.TryGetInstance(serviceType);
            if(instance == null && !serviceType.IsAbstract)
            {
                _container.Configure(c => c.AddType(serviceType,serviceType));
                instance = _container.TryGetInstance(serviceType);
            }
        开发者_如何学Python    return instance;

        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _container.GetAllInstances(serviceType).Cast<object>();
        }
    }

here is the IPostRepo looks like

public interface IPostRepo
    {
        bool CreatePost(Post newPost);

        List<Post> ShowAllPosts();

        Post FindPostById(int postId);

        Post EditPost(Post editPost);

        UserPostCommentViewModel FindAllPostComments(int postId);

        int? AddPlusOneToNumberOfViews(int postId);
    }

thx martin for your help


No. Like I said in your other question, take out the Controller Activator ... unless you are using it for a purpose (which it doesn't seem like you are).

Also, this line is plain WRONG:

x.ForRequestedType<AccountController>().TheDefault.Is.
              ConstructedBy(() => new AccountController(new UserRepo()));

You should not be using new for your UserRepo ... that is what the line above is taking care of:

x.For<IUserRepo>().Use<UserRepo>();

If you take out the ControllerActivator, you should have a nice start to an MVC app.

0

精彩评论

暂无评论...
验证码 换一张
取 消